javascript - 如何修复功能已在 Jasmine 中发现错误
问题描述
我有 3 个测试,每个测试不同的方法。
it('test function1', function() {
spyOn(document, 'getElementById');
// ... some code to test function1
expect(document.getElementById).toHaveBeenCalled();
});
it('test function2', function() {
spyOn(document, 'getElementById');
// ... some code to test function2
expect(document.getElementById).toHaveBeenCalled();
});
it('test function3', function() {
spyOn(document, 'getElementById');
// ... some code to test function3
expect(document.getElementById).toHaveBeenCalled();
});
但是当我运行这些测试时,我收到以下错误:getElementById has already been spied upon
. 有人可以解释为什么即使间谍在不同的测试套件中我也会收到此错误以及如何修复它。
解决方案
一旦您对某个方法进行了一次监视,就不能再次对其进行监视。如果您只想检查它是否在每个测试中被调用,只需在测试开始时创建间谍,然后重置调用afterEach
:
spyOn(document, 'getElementById');
afterEach(() => {
document.getElementById.calls.reset();
});
it('test function1', function() {
// ... some code to test function1
expect(document.getElementById).toHaveBeenCalled();
});
it('test function2', function() {
// ... some code to test function2
expect(document.getElementById).toHaveBeenCalled();
});
it('test function3', function() {
// ... some code to test function3
expect(document.getElementById).toHaveBeenCalled();
});
推荐阅读
- json - Powershell 显示 JSON-object 和 ADDRESS-property 的错误输出
- asp.net-core-webapi - 如何在 web api 中编写连接并从两个表中检索字段
- python-3.x - 将一列中的数字添加到熊猫数据框中另一列中的日期
- android - 这可能吗,GNOME (lib)Clutter with OpenGL ES & Vulkane?
- wget - 如何让 wget 忽略错误而不是完全停止?
- css - Chrome CSS 线性渐变 - 应用 1 像素块消失但在缩放时可见
- python - 使用来自 crontab 的参数(来自 python 中的 argparse)运行 python 脚本
- java - 无法在 RecyclerView 中显示从 Firebase 检索到的数据
- powershell - Powershell 脚本杀死所有 3 分钟无响应的 PID
- c# - 如何在 Startup.cs 中配置我自己的 NuGet 包