【问题标题】:How do I test that the method has been called in jasmine?如何测试该方法是否已在 jasmine 中调用?
【发布时间】:2012-05-30 13:50:37
【问题描述】:

我对监视茉莉花有点困惑。我有这样的代码,但我不知道如何测试它。

var params = {
    param1: "",
    param2: "link",
    param3: "1", 
    param4 : "1"
};
var func = new myFunction(params );
func.doSomething();

如何测试 func.doSomething 是否已被调用。

这是我目前写的测试

describe("Library", function() {

  beforeEach(function() {
  });

  it("should include correct parameters", function() {
      expect(params.param1).toEqual("");
      expect(params.param2).toEqual("link");
      expect(params.param3).toEqual("1");
      expect(params.param4).toEqual("1");
  });

  it("should show that method doSomething is called with zero arguments", function() {
          // I'm not sure how to write test for this.
  });
});

【问题讨论】:

    标签: javascript testing bdd jasmine


    【解决方案1】:

    我想你想用toHaveBeenCalledWith():

    it("should show that method doSomething is called with zero arguments", function() {
        // Ensure the spy was called with the correct number of arguments
        // In this case, no arguments
        expect(func.doSomething).toHaveBeenCalledWith();
    });
    

    【讨论】:

    • 感谢您的回答。这就是我所做的。 spyOn(func, "doSomething"); func.doSomething();期望(func.doSomething).toHaveBeenCalled();但是我有一个愚蠢的问题,这是否意味着在测试中调用了 func.doSomething() 而不是测试真实代码的行为?我对此很陌生,所以请原谅我提出愚蠢的问题。
    • 如果你想指定多少次:expect(component.func).toHaveBeenCalledTimes(1);
    【解决方案2】:

    如果 spy 函数只被调用过一次,使用toHaveBeenCalledOnceWith matcher:

    expect(mySpy).toHaveBeenCalledOnceWith('', 'link', "1", "1");
    

    它结合了toHaveBeenCalledTimes(1)toHaveBeenCalledWith() 匹配器。

    带有Jasmine 3.6

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多