Kemal Tezer Dilsiz
Kemal Tezer Dilsiz

Reputation: 4009

How to spyOn an exported standalone function using javascript jest?

It is a very simple scenario but I've struggled to find an answer for it.

helpers.ts:

export function foo() {
    bar();
}

export function bar() {
    // do something
}

helpers.spec.ts:

import { foo, bar } from "./helpers";

describe("tests", () => {
    it("example test", () => {
        const barSpy = // how can i set this up?
        foo();
        expect(barSpy).toHaveBeenCalled();
    });
});

I can't do const spy = jest.spyOn(baz, 'bar'); because I don't have a module/class to put in place of "baz". It is just an exported function.

Edit: Jest mock inner function has been suggested as a duplicate but unfortunately it doesn't help with my scenario.

Solutions in that question:

helpers.spec.ts:

import * as helpers from "./helpers";

describe("tests", () => {
    it("example test", () => {
        const barSpy = jest.spyOn(helpers, 'bar');
        foo();
        expect(barSpy).toHaveBeenCalled();
    });
});

results in:

expect(jest.fn()).toHaveBeenCalled()

Expected number of calls: >= 1
Received number of calls:    0

Upvotes: 3

Views: 6949

Answers (1)

Ron
Ron

Reputation: 6735

This is the closed solution:

export function bar() {
  // do something
}

export function foo() {
  exports.bar();   // <-- have to change to exports.bar() instead of bar()
  // or this.bar(); would also work.
}

import * as utils from './utils';

describe('tests', () => {
  it('example test', () => {
    const barSpy = jest.spyOn(utils, 'bar');
    utils.foo();
    expect(barSpy).toHaveBeenCalled();
  });
});

Or take a look this duplicated question

Upvotes: 9

Related Questions