【问题标题】:Jasmine spyOn NodeJSJasmine spyOn NodeJS
【发布时间】:2016-04-26 13:54:51
【问题描述】:

我想知道你是否可以帮助我。我正在使用带有 NodeJS 的 Jasmine 间谍。我正在尝试模拟一个函数,该函数被另一个函数调用。但模拟看起来并不像它正在工作。

api.js

function hello() {
    greeting();
}

function greeting() {
    console.log("welcome!");
    console.log("But instead it prints this!");
}

module.export = {
    hello    : hello,
    greeting : greeting
}

api-spec.js

const api = require("./api")

describe("testing jasmine spies", function() {
    it("mocks the greeting", function() => {
        spyOn(api, "greeting").and.callFake(function() {
            console.log("it should print this, since I am mocking it...")
        });

        api.hello();
    });
});

如您所见,我模拟了greeting,它被hello 调用。因此,当我从规范中调用 hello 时,我希望它调用我的 greeting 函数的模拟版本。但它改为调用实际的实现。

你能帮帮我吗?

【问题讨论】:

  • 我在 nodeJS 中遇到了同样的问题,在对等函数上使用 this 仍然不会为我触发 spyOn 模拟

标签: node.js jasmine mocha.js sinon chai


【解决方案1】:

请考虑如何测试this.greeting()greeting() 函数调用的区别。

在全局/窗口范围内执行

function hello() {
  greeting();
}

function greeting() {
  console.log('original greeting')
}

api = {
  hello: hello,
  greeting: greeting
}

describe("jasmine spies on global object", function() {
  it("mocks the window.greeting()", function() {
    spyOn(window, "greeting").and.callFake(function() {
      console.log("stubbed `api.greeting()`")
    });
    api.hello();
    expect(window.greeting).toHaveBeenCalled();
  });
});
<link href="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" />
<script src="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script>

在对象上下文中执行

function hello() {
  this.greeting();
}

function greeting() {
  console.log('original greeting')
}

api = {
  hello: hello,
  greeting: greeting
}

describe("jasmine spies on object", function() {
  it("mocks the api.greeting()", function() {
    spyOn(api, "greeting").and.callFake(function() {
      console.log("stubbed `api.greeting()`")
    });
    api.hello();
    expect(api.greeting).toHaveBeenCalled();
  });
});
<link href="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" />
<script src="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script>

【讨论】:

  • 我不确定我明白你的意思吗? spyOn(api, "greeting") 本质上是在说 api.greeting()?。 hello() 调用全局函数 greeting()app.js 中没有名为 api 的实例
  • @AAli 是的,它明确表示 api.greeting() - 但 api.greetinggreeting() 不同 - 研究证明它的测试
猜你喜欢
  • 1970-01-01
  • 2015-08-22
  • 2015-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多