简体   繁体   中英

How to mock instantiated object with Jest

I have a file (src/dclient) that does this:

import DataClient from 'src/clients/data'

const DClient = new DataClient({ id: 'xxx' })
export default DClient

And I have a file (which I am trying to test) that does this:

import DClient from src/dclient

// Some code

DClient.alert('hello')

I am trying to write expectations on Dclient.alert but failing to do so. I have tried to set up the jest test as:

alertMock = jest.fn();
require('src/dclient').alert = alertMock

But this is not working when I check alertMock.mock.calls even though I know it has been called. I think because dclient returns an instance and actually doesn't have alert defined on it.

How can I set up this jest so I can write expectations on alert?

There are several ways to test this.

The way you are trying works fine, you just need to change it to this:

test('code', () => {
  const alertMock = jest.fn();
  require('src/dclient').default.alert = alertMock;  // <= mock alert on 'default'

  require('./code');  //  <= require the code that calls DClient.alert('hello')
  expect(alertMock).toHaveBeenCalledWith('hello');  // Success!
})

...because src/dclient is an ES6 module with a default export.


The approach I would probably use is to mock the alert function on the DataClient class:

import DataClient from 'src/clients/data';

test('code', () => {
  const alertSpy = jest.spyOn(DataClient.prototype, 'alert');
  alertSpy.mockImplementation(() => {});

  require('./code');  //  <= require the code that calls DClient.alert('hello')
  expect(alertSpy).toHaveBeenCalledWith('hello');  // Success!
})

Jest has a really well-made auto-mocking feature , which generates jest.fn() for each method on the exported object, so you can just:

import DClient from 'src/dclient'; // import the module
jest.mock('src/dclient'); // generate auto-mock

describe('alert', () => {
    beforeAll(() => {
        DClient.alert.mockReturnValue(true);
        // ^ not really needed in the alert case, but you'll get
        // error if the exported object doesn't have alert method
    });

    it('should have been called', () => {
        DClient.alert('hello');
        expect(DClient.alert).toHaveBeenCalledWith()
    });
});

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