0

My test function is as follows:

const testLibrary = require("./test");

describe("Top Test", function() {

    it("should test function", function(done) {
        testLibrary.print();
        done();

    });


});

test.ts has the following two functions:

export function stubMe() {
    console.log("original function");
}

export function print() {
    stubMe();
}

When I run the test, it prints: 'original function'

I now try to stub my test as follows:

const testLibrary = require("./test");


const sinon = require("sinon");

const stubMe = sinon.stub(testLibrary, "stubMe");
stubMe.yields();

describe("Top Test", function() {

    it("should test function", function(done) {
        testLibrary.print();
        done();

    });


});

My test function still prints 'original function' indicating that the function hasn't been stubbed.

How do I stub the stubMe function?

Update:

I have modified my code based on Ankit's solution below to:

  const sinon = require("sinon");
  const testLibrary = require("./test");

  testLibrary.stubMe();

  const stubMe = new sinon.stub(testLibrary, "stubMe").callsFake(function () {
    console.log("console from stub");
  });

  testLibrary.stubMe();


  describe("Top Test", function () {

    it("should test function", function (done) {
      testLibrary.print();
      done();

    });

  });

Oddly, this prints:

original function
console from stub


  Top Test
original function

Why does the stub revert during the test?

Hoa
  • 19,858
  • 28
  • 78
  • 107
  • Because in one case you're calling `testLibrary.stubMe()` and in another case you're calling `stubMe()`. This is what the answer says. – Estus Flask Jun 29 '18 at 12:10

2 Answers2

0

Use callsFake() instead of yields() like:

 const testLibrary = require('./test');

  const sinon = require('sinon');

  const stubMe = new sinon.stub(testLibrary, 'stubMe');
  stubMe.callsFake(function () {
    console.log('console from stub');
  });

  describe('Top Test', function () {

    it('should test function', function (done) {
      testLibrary.print();
      done();

    });

  });

Here is the output for the above test: enter image description here

Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

There is no way how the function can be spied or mocked. stubMe is referred directly in same module.

As explained in related Jest question, a way to improve testability is to move functions to different modules:

// one module
export function stubMe() {
    console.log("original function");
}

// another module
import { stubMe } from '...';
export function print() {
    stubMe();
}

In this case testLibrary.stubMe can be spied or mocked, but only if non-native ES modules are in use, because ES module exports are read-only in native implementation.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565