如何测试在jasmine中调用该方法?

时间:2012-05-30 13:50:37

标签: javascript testing bdd jasmine

我对茉莉花的间谍有点困惑。我有这样的代码,但我不确定如何测试它。

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.
  });
});

2 个答案:

答案 0 :(得分:9)

我认为你想使用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();
});

答案 1 :(得分:0)

如果间谍函数仅被调用一次,请使用toHaveBeenCalledOnceWith匹配器:

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

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

附带Jasmine 3.6:发布文档