如何在另一个方法中创建的对象上使用 Jasmine 间谍?

2022-01-11 00:00:00 testing jasmine javascript spy

鉴于以下代码片段,您将如何创建 Jasmine spyOn 测试以确认 doSomething 在您运行 MyFunction 时被调用?

Given the following code snippet, how would you create a Jasmine spyOn test to confirm that doSomething gets called when you run MyFunction?

function MyFunction() {
    var foo = new MyCoolObject();
    foo.doSomething();
};

这是我的测试的样子.不幸的是,在评估 spyOn 调用时出现错误:

Here's what my test looks like. Unfortunately, I get an error when the spyOn call is evaluated:

describe("MyFunction", function () {
    it("calls doSomething", function () {

        spyOn(MyCoolObject, "doSomething");
        MyFunction();
        expect(MyCoolObject.doSomething).toHaveBeenCalled();

    });
});

Jasmine 此时似乎无法识别 doSomething 方法.有什么建议吗?

Jasmine doesn't appear to recognize the doSomething method at that point. Any suggestions?

推荐答案

当您调用 new MyCoolObject() 时,您会调用 MyCoolObject 函数并使用相关原型.这意味着当您 spyOn(MyCoolObject, "doSomething") 时,您不是在 new 调用返回的对象上设置间谍,而是在可能的 MyCoolObject 函数本身的>doSomething 函数.

When you call new MyCoolObject() you invoke the MyCoolObject function and get a new object with the related prototype. This means that when you spyOn(MyCoolObject, "doSomething") you're not setting up a spy on the object returned by the new call, but on a possible doSomething function on the MyCoolObject function itself.

您应该能够执行以下操作:

You should be able to do something like:

it("calls doSomething", function() {
  var originalConstructor = MyCoolObject,
      spiedObj;
  spyOn(window, 'MyCoolObject').and.callFake(function() {
    spiedObj = new originalConstructor();
    spyOn(spiedObj, 'doSomething');
    return spiedObj;
  });
  MyFunction();
  expect(spiedObj.doSomething).toHaveBeenCalled();
});

相关文章