使用Jasmine进行单元测试:testE的spyOn()看不到beforeEach()中的代码

par*_*ton 4 javascript unit-testing jasmine

一般来说是单元测试的新手,特别是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");
      });

    });

  });
});
Run Code Online (Sandbox Code Playgroud)

文件解释了使用,但没有上下文的spyOn(),所以如果我创建了一个错误或我不知道如果我在不知不觉中走功能的优势.

如果有人认为它对诊断有任何影响,我可以发布构造函数,但我可以向你保证这很简单.

我确信使用一些基本的单元测试概念是一个简单的解决方案,我必须要努力学习.提前致谢.

PS 我意识到我正在测试的是那个失败的规范并不是我所描述的.我正在通过API指南,寻找一种方法来获取函数调用中的arguments数组,所以我可以进行特定的测试arguments[0].提示是值得赞赏的,但不是必需的.我会弄清楚.

Zee*_*cer 7

简短的回答:不,在每个和间谍不相容之前

如果你想让间谍了解这个电话,你必须在打电话之前打电话.如果您不希望干扰其默认行为,可以使用spyOn(object,'function').和CallThrough().

长答案:伪造/模拟/存根/间谍框架经常工作的方式是使用模拟框架可以控制的方法替换您调用的方法.在用间谍替换之前对该函数的任何调用都无法被观察到.这是一件好事,虽然有点不方便,


And*_*rle 5

它导致你窥视窗户.在你打电话后按钮.我不完全确定间谍做了什么,但毕竟它取代了你用另一个函数监视的函数,它可以检查函数是否被调用,并且传递了什么参数.在开始测试之前创建Button时,会window.button调用原始函数.然后用spy替换该函数并测试spy被调用,因此你的测试必须失败.

似乎要么在测试中创建Button,要么在调用beforeEach函数中的新Button之前创建间谍.