A Ali A Ali - 1 month ago 16
Node.js Question

Jasmine spyOn NodeJS

I was wondering if you can help me. I am using Jasmine spies with NodeJS. I am trying to mock a function, which gets called by another function. But the mock does not look like it is working.

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


As you can see, I mock
greeting
, which gets called by
hello
. So, when I call hello from my spec, I expect it to call the mocked version of my
greeting
function. But it calls the actual implementation instead.

Can you please help me?

Answer

Please consider the difference how to test this.greeting() and greeting() function call.

Executed in global / window scope

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>

Executed in object context

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>