2012-01-11 35 views
4

单元测试新手,尤其是Jasmine。使用Jasmine进行单元测试:beforeEach()中的代码未在测试的spyOn中看到()

我在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]上进行特定的测试。提示是赞赏,但不是必要的。我会弄清楚。

回答

6

简短的回答:没有,之前每个和间谍并不矛盾

打电话之前,如果你想间谍知道关于呼叫你必须间谍。如果你不想干扰它的默认行为,你可以使用spyOn(object,'function')和andCallThrough()。

长答案:伪造/嘲讽/存根/间谍框架经常工作的方式是用嘲笑框架可以控制的方法替换您调用的方法。在被间谍替换前,任何对该功能的调用都不能被观察到。这是一件好事,尽管稍微不方便,

+0

切换顺序和CallThrough()做到了。 +1并被接受。非常感谢。 – parisminton 2012-01-21 01:39:46

+0

@parisminton。我在jamsine测试用例上发布了一个问题。 http://stackoverflow.com/questions/26583283/jasmine-junit-testing-of-delegate-callback-of-function-args ..真正appriciate如果你能帮助。问候 – 2014-10-28 13:58:18

4

它的原因是你调用后在window.Button上侦听。我不完全确定间谍是做什么的,但毕竟它取代了你用另一个函数来监视的函数,它可以检查被调用的函数以及传递了什么参数。在开始测试之前创建Button时,调用原始的window.button函数。然后你用间谍替换这个功能并测试间谍被调用,所以你的测试必须失败。

似乎要么在测试本身中创建您的按钮,要么在您调用beforeEach函数中的新按钮之前创建您的间谍。

+0

+1。事实上,我将'spyOn()'调用移到'beforeEach()'函数中,它的工作原理与您的建议完全相同。谢谢。 – parisminton 2012-01-21 01:44:38

相关问题