user1486133
user1486133

Reputation: 1487

Mocking a function from an imported file, but also checking that it has been called

The file I'm testing imports a func from another file. In order to stop that outside func from running, I mocked the import:

jest.mock("./anotherFile", () => ({
  outsideFunc: jest.fn()
}));

However I now need to write a unit test for a function to check that outsideFunc gets called. Don't care about the return, just that it was called at all.

System under test

function myFunc() {
  outsideFunc();
}

The test

describe("Testing myFunc", () => {
    it("Should call outsideFunc", () => {
      myFunc();
      expect(outsideFunc).toHaveBeenCalled();
    });
  });

When I run the test, I get:

ReferenceError: outsideFunc is not defined

I understand why I'm getting this error, normally I'd have something like

const outsideFuncMock = jest.fn() 

But in this case I already mocked the function when I did the import to stop it being called, so I'm a bit lost.

My test suite

jest.mock("./anotherFile", () => ({
  outsideFunc: jest.fn()
}));

describe("Testing myFunc", () => {
  it("Should call outsideFunc", () => {
    myFunc();
    expect(outsideFunc).toHaveBeenCalled();
  });
});

Upvotes: 0

Views: 622

Answers (1)

Lin Du
Lin Du

Reputation: 102517

You are almost there, here is the solution:

folder structure:

.
├── anotherFile.ts
├── index.spec.ts
└── index.ts

0 directories, 3 files

index.ts:

import { outsideFunc } from './anotherFile';

export function myFunc() {
  outsideFunc();
}

anotherFile.ts:

export const outsideFunc = () => 1;

index.spec.ts:

import { myFunc } from './';
import { outsideFunc } from './anotherFile';

jest.mock('./anotherFile.ts', () => ({
  outsideFunc: jest.fn()
}));

describe('Testing myFunc', () => {
  it('Should call outsideFunc', () => {
    myFunc();
    expect(jest.isMockFunction(outsideFunc)).toBeTruthy();
    expect(outsideFunc).toHaveBeenCalled();
  });
});

Unit test result with 100% coverage:

 PASS  src/stackoverflow/58413956/index.spec.ts
  Testing myFunc
    ✓ Should call outsideFunc (4ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.ts |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.129s, estimated 7s

Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58413956

Upvotes: 1

Related Questions