【问题标题】:How do I use jest.mock within a describe or it block?如何在 describe 或 it 块中使用 jest.mock?
【发布时间】:2021-06-24 20:09:08
【问题描述】:

我正在使用打字稿和玩笑。我有两个文件users.service.ts,它导入producer.ts。我想在 producer.ts 中模拟一个函数。这很好用

import { sendUserData } from './users.service';

const processDataSpy = jest.fn().mockImplementation(() => {
    throw new Error('failed');
  });

  jest.mock('../users/manager', () => ({
    sendEvent: async (arg1: string, arg2: string, arg3: any) =>
      processDataSpy(arg1, arg2, arg3),
  }));


describe('users.service', () => {

  it('invokes endpoint and returns proper data if unsuccessful', async () => {

    const result = await sendUserData(
      data
    );

    expect(result).toBe(false);

  });

但是,我想在 processDataSpy 中模拟不同的结果。我正在测试上面抛出错误的案例,但我想测试没有抛出错误的案例。如何测试多个案例?在我的“it”块中移动“jest.mock”会破坏测试......

  it('invokes endpoint and returns proper data if unsuccessful', async () => {
    
    jest.mock('../users/manager', () => ({
      sendEvent: async (arg1: string, arg2: string, arg3: any) =>
        processDataSpy(arg1, arg2, arg3),
    }));
    ...
    const result = await sendUserData(
      data
    );

    expect(result).toBe(false);

  });

我收到一条错误消息,表明不再使用或启动模拟。如何在“describe”或“it”块中使用“jest.mock”?

【问题讨论】:

    标签: typescript unit-testing mocking ts-jest


    【解决方案1】:

    您可以在ittest 块内使用processDataSpy.mockImplementation

    // Optionally reset the mock before each test
    beforeEach(() => {
      processDataSpy.mockReset(); 
    });
    
    it('Another use case', async () => {
        
        processDataSpy.mockImplementation(() => {
          throw new Error('Another error');
        })
       
        const result = await sendUserData(
          data
        );
    
        expect(result).toBe(false);
    });
    

    【讨论】:

      猜你喜欢
      • 2021-11-29
      • 2020-12-19
      • 2017-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-24
      • 1970-01-01
      相关资源
      最近更新 更多