【问题标题】:How to mock instantiated object with Jest如何用 Jest 模拟实例化对象
【发布时间】:2019-03-25 11:43:52
【问题描述】:

我有一个执行此操作的文件 (src/dclient):

import DataClient from 'src/clients/data'

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

而且我有一个文件(我正在尝试测试)这样做:

import DClient from src/dclient

// Some code

DClient.alert('hello')

我正在尝试在Dclient.alert 上写期望,但没有这样做。我试图将开玩笑的测试设置为:

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

但是当我检查alertMock.mock.calls 时这不起作用,即使我知道它已被调用。我认为是因为 dclient 返回了一个实例,实际上并没有在其上定义警报。

如何设置这个笑话,以便我可以在警报时写下期望?

【问题讨论】:

    标签: javascript testing mocking jestjs


    【解决方案1】:

    有几种方法可以对此进行测试。

    您尝试的方式工作正常,您只需将其更改为:

    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!
    })
    

    ...因为src/dclient 是一个带有default 导出的ES6 模块。


    我可能会使用的方法是在 DataClient 类上模拟 alert 函数:

    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!
    })
    

    【讨论】:

    • 我在使用 require('src/dclient').alert = alertMock 我应该一直在使用 require('src/dclient').default.alert。谢谢!
    【解决方案2】:

    Jest 有一个制作精良的auto-mocking feature,它为导出对象上的每个方法生成jest.fn(),所以你可以:

    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()
        });
    });
    

    【讨论】:

    • 执行此操作时,我收到此错误jest.fn() value must be a mock function or spy
    • 请注意 DClient 返回另一个文件的实例...这不会改变您模拟它的方式吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    • 2018-06-21
    • 2017-12-20
    • 1970-01-01
    • 2019-10-27
    相关资源
    最近更新 更多