我正在开发一个 jQuery 插件,它循环显示大量图像。我正在编写一些测试,想测试 src 属性是否总是在应该更改的时候更改。问题是
- 原始图像包含在要循环的图像列表中
- 页面中使用的图像是随机选择的
- 周期由 setInterval 控制,由于系统性能等原因,有点不可预测
因此有时测试可能会失败,因为原始图像是从可用图像中随机选择的,因此看起来好像没有发生变化。
如何避免此类误报?
最佳答案
正如我们在 JavaScript 中一样,您可以像这样覆盖 Math.random:
describe('some suite', function () {
it('Math.random should equal 1', function () {
var origRandom = Math.prototype.random;
Math.prototype.random = function(){return 1};
expect(Math.random()).toEqual(1);
Math.prototype..random = origRandom;
});
it('Math.random should equal 1 using jasmine', function () {
spyOn(Math, 'random').andReturn(1)
expect(Math.random()).toEqual(1);
});
});
另一种方法是将随机数传递给您的渲染函数,而不是在您要测试的函数内部创建
关于javascript - 避免 JavaScript 测试中的误报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8797099/