简体   繁体   中英

How to mock a directly-imported function using Jest?

I'm trying to verify that my method is correctly invoking another, imported method. For the life of me, I can't figure out how to mock the imported method using Jest.

Method I want to test

LandingPageManager.ts

import {getJSON} from './getJSON';

public fetchData(url: string) {
    getJSON(url);
}

Method I want to mock

getJSON.ts

export function getJSON(url: string) {
    // XHR requests logic 
}

Test method

LandingPageManager.test.ts

import 'jest';
import {getJSON} from '../../../src/web/getJSON';
import {LandingPageManager} from '../../../src/web/LandingPageManager';

describe('fetchData', () => {
  let manager = new LandingPageManager();
  it('passes the correct URL to getJSON', () => {
    const getJsonSpy = jest.mock('../../../src/web/getJSON', jest.fn());

    manager.fetchData('sampleValue');
    expect(getJsonSpy).toHaveBeenCalledWith('sampleValue');

    getJsonSpy.restoreAllMocks();
  });
});

Error I'm getting

 jest.fn() value must be a mock function or spy

I've tried setting up the mock a variety of different ways. But I can't seem to get the syntax right.

Can anyone help point me in the right direction? I feel like this should be possible.

Finally figured out the answer.

Nothing needed to change in the source code (either the imported module or the class under test).

The import needed to change from:

import {getJSON} from '../../../src/web/getJSON';

to:

import * as getJSON from '../../../src/web/getJSON';

And then I was able to directly specify the function for spying with:

const jsonSpy = jest.spyOn(getJSON, 'getJSON');

Fixed test case

Here's how it all works together now.

LandingPageManager.test.ts

import 'jest';
// **** 1.) Changed the below line: ****
import * as getJSON from '../../../src/web/getJSON';
import {LandingPageManager} from '../../../src/web/LandingPageManager';

describe('fetchData', () => {
  let manager = new LandingPageManager();
  it('passes the correct URL to getJSON', () => {
    // **** 2.) Can now specify the method for direct mocking ****
    const jsonSpy = jest.spyOn(getJSON, 'getJSON');

    manager.fetchData('sampleValue');
    expect(getJsonSpy).toHaveBeenCalledWith('sampleValue');

    getJsonSpy.restoreAllMocks();
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM