【发布时间】:2012-01-11 19:22:55
【问题描述】:
单元测试新手,尤其是 Jasmine。
我在beforeEach() 回调中设置了一个变量,但它似乎不适用于第二次测试。它应该在其上下文中的 每个 测试之前触发初始化内容,对吗?我确定我的spyOn() 电话是罪魁祸首,但我不知道如何解决。
评论解释通过和失败:
describe("Test suite for my library", function () {
var html,
body,
play,
...
// custom matcher...
beforeEach(function () {
this.addMatchers({
toBeInstanceOf : function (constructr) {
return this.actual instanceof constructr;
});
});
});
describe("Within the Button object", function () {
beforeEach(function () {
play = new Button("play", false);
});
describe("play", function () {
// This test passes, as expected...
it("should be an instance of the Button object", function () {
expect(play).toBeInstanceOf(Button);
});
});
describe("play.name", function () {
// This test failed with the message
// "Expected spy Button to have been called
// with [ 'play', false ] but it was never called."
it("should be the first argument passed to the Button constructor", function () {
spyOn(window, "Button");
play = new Button("play", false); // ...until I added this line. Now it passes.
expect(window.Button).toHaveBeenCalledWith("play", false);
});
// This test passes, even if the one above fails.
it("should be 'play'", function () {
expect(play.name).toBe("play");
});
});
});
});
documentation 解释了 spyOn() 的用法,而不是上下文,所以我无法判断我是否创建了错误,或者我是否在不知不觉中利用了某个功能。
如果有人认为它对诊断有任何影响,我可以发布构造函数,但我可以向你保证它非常简单。
我确信这是一个使用一些基本单元测试概念的简单解决方法,我必须通过艰苦的方式学习。提前致谢。
P.S. 我意识到我在那个失败的规范中测试的不是我所描述的。我正在阅读 API 指南,寻找一种在函数调用中获取参数数组的方法,因此我可以对 arguments[0] 进行特定测试。提示表示赞赏,但不是必需的。我会想办法的。
【问题讨论】:
标签: javascript unit-testing jasmine