Sean
Sean

Reputation: 689

Nested mock functions in Jest

I'm currently trying to test out mocking some of my jest functions. One of the issues I'm having is trying to mock out a function that is called inside of another function. Here is a high-level example of what I'm trying to do:

//Apple.js
function Apple(){
   return Orange(1, 2);
}

function Orange(arg1, arg2){
   return (arg1 + arg2);
}

I want to test the Apple function without making an actual call to Orange. What would be the code to mock out my orange function in a .spec.js file to make something like this happen? I was thinking something like the following but I doubt it:

//Apple.spec.js
import Apple from "Apple.js";
it("Should run Apple", () => {
   global.Orange = jest.fn().mockImplementation(() => {return 3});
   expect(Apple()).toEqual(3);
});

It's a really simple example but knowing this would definitely help me understand the next step in my project. I hope to hear from the community soon!

Upvotes: 5

Views: 6665

Answers (1)

Lin Du
Lin Du

Reputation: 102207

Here is the solution:

Apple.js:

function Apple() {
  return Orange(1, 2);
}

function Orange(arg1, arg2) {
  return arg1 + arg2;
}

exports.Apple = Apple;
exports.Orange = exports.Orange;

Apple.spec.js:

const functions = require('./Apple.js');

describe('Apple', () => {
  it('Should run Apple', () => {
    functions.Orange = jest.fn().mockImplementation(() => {
      return 3;
    });
    expect(functions.Apple()).toEqual(3);
  });
});

Unit test result with 100% coverage:

PASS  src/stackoverflow/51275648/Apple.spec.js
  Apple
    ✓ Should run Apple (4ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 Apple.js |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.312s

Here is the completed demo: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/51275648

Upvotes: 2

Related Questions