【问题标题】:How to reset a spy or mock in jest如何在玩笑中重置间谍或模拟
【发布时间】:2020-06-23 08:21:39
【问题描述】:

我在我的测试用例文件中模拟了一个函数。

MyService.getConfigsForEntity = jest.fn().mockReturnValue(
    new Promise(resolve => {
        let response = [];
        resolve(response);
    })
);

现在我希望该文件中的所有测试用例都使用这个模拟

describe('Should render Component Page', () => {
    it('should call the API', async () => {
        const {container} = render(<MyComp entityName='entity1'/>);
        await wait(() => expect(MyService.getConfigsForEntity).toHaveBeenCalled());
    });
});

唯一的问题是只有一个测试用例我想以不同的方式模拟返回值。

但是之前和之后的所有其他测试用例都可以使用全局模拟。

describe('Should call API on link click', () => {
    it('should call the API on link click', async () => {
       const spy = jest.spyOn(MyService, 'getConfigsForEntity ').mockReturnValue(
           new Promise(resolve => {
           let response = [{
               "itemName": "Dummy"
           }];
           resolve(response);
        });
        const {container} = render(<MyComp entityName='entity1'/>);
        await wait(() => expect(spy).toHaveBeenCalled());
        spy.mockClear();
    });
});

问题是,一旦我在一个测试用例中以不同方式模拟函数,该测试用例之后使用全局模拟的所有其他测试用例都失败了,

但它只有在我将测试用例放在所有其他测试用例之后才有效。

我做错了什么?

【问题讨论】:

    标签: reactjs unit-testing jestjs react-testing-library spy


    【解决方案1】:

    你可以试试mockRestore():

    beforeEach(() => {
      spy.mockRestore();
    });
    

    【讨论】:

    • @StrugglingCoder 这个解决方案对你有用吗?
    【解决方案2】:

    你试过了吗?

      beforeEach(() => {
         jest.clearAllMocks();
      })
    

    【讨论】:

      猜你喜欢
      • 2020-05-26
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 2021-01-06
      • 2020-02-08
      • 2020-10-20
      • 1970-01-01
      • 2022-10-06
      相关资源
      最近更新 更多