Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • Move to separate module: I cannot do this for my scenario. If I am testing every function in my application, this would result in me creating 10s of new files which is not ideal. (To clarify, I think this solution would work but I cannot use it for my scenario. I am already mocking a separate file function successfully in this test file.)

  • Import the module into itself:

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
like image 682
Kemal Tezer Dilsiz Avatar asked Oct 30 '25 20:10

Kemal Tezer Dilsiz


1 Answers

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

like image 142
Ron Avatar answered Nov 01 '25 10:11

Ron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!