这是我的测试
describe("setTimer", function () {
it("set status timer values from parameters and sets timer.visible to true", function(){
var boxNumber = 1,
time = 15;
myObject.setTimer(boxNumber, time);
expect(anotherObject.status.timer.boxNum).toBe(boxNumber);
expect(anotherObject.status.timer.seconds).toBe(time);
})
});
这是代码
setTimer: function (boxNum, seconds) {
anotherObject.status.timer.boxNum = boxNum;
anotherObject.status.timer.seconds = seconds;
anotherObject.status.timer.visible = true;
},
这是我收到的错误
TypeError: Cannot read property 'timer' of undefined
我尝试使用 anotherObject = {}
设置对象 我尝试设置 anotherObject.status = {}
最后尝试设置 anotherObject.status.timer = { }
,但是我仍然收到错误。有什么想法,我如何模拟该对象?
最佳答案
如果不知道“anotherObject”的构造方式/位置,我认为您需要在测试中执行 setTimer 函数之前初始化“anotherObject”。
“anotherObject”上是否有 init() 或 setup() 函数可以为您初始化“timer”对象?
虽然该方法看起来只是试图确保该方法正在设置所有相应的属性。
在测试中调用 setTimer 之前,您可以执行以下操作
describe("setTimer", function () {
it("set status timer values from parameters and sets timer.visible to true", function(){
var boxNumber = 1,
time = 15;
//Initialize the anotherObject
anotherObject.status = { timer : {} }
myObject.setTimer(boxNumber, time);
expect(anotherObject.status.timer.boxNum).toBe(boxNumber);
expect(anotherObject.status.timer.seconds).toBe(time);
})
});
当然,这需要注意的是,您现在已经使用全局范围在测试中定义了“anotherObject”(因为排除 javascript 中任何变量定义上的 var 使其成为全局范围)。这可能会影响其他期望以某种方式设置计时器对象的测试用例,但您的测试用例现在已分别将计时器值设置为 1 和 15(可能有很多其他值,全部取决于测试用例正在执行的操作)。
因此,为了解决这个问题,在测试开始或结束时重置“anotherObject”将有助于消除污染
afterEach(function(){
anotherObject.status = { timer : {} }
})
或
beforeEach(function(){
anotherObject.status = { timer : {} }
})
当然,如果您在“anotherObject”上有一个可以使用的 init()、create() 或 setup() 函数,那么它当然会给您带来更真实的结果,因为该对象将更接近于它的实际情况看起来像在生产中。
关于javascript - 用 jasmine 测试嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22847663/