【问题标题】:How to mock multiple values from a mocked module?如何从模拟模块模拟多个值?
【发布时间】:2020-11-30 21:58:11
【问题描述】:

我正在尝试模拟模块“jwt-decode”,我可以使用以下方法成功模拟一个返回值:

 jest.mock('jwt-decode', () => () => ({ data: { userRole: 2, checklist: mockUser.account.checklist }}))

这适用于需要解码的 jwt 以产生 2 的 userRole 的测试。但是,我的下一个测试需要 userRole 为 1,这就是问题出现的地方。

是否有适当的方法将 userRole 作为第一个测试实例返回 2 并为下一个测试实例返回 1?

【问题讨论】:

    标签: javascript reactjs jestjs


    【解决方案1】:

    您可以通过在模拟函数上调用 mockImplementationmockImplementationOnce 并使用新实现作为参数来更改模拟函数的模拟实现,详细信息如下:https://jestjs.io/docs/en/mock-functions#mock-implementations

    在你的情况下是这样的:

    import jwt_decode from 'jwt-decode';
    
    jest.mock('jwt-decode', () => jest.fn(() => ({
        data: { userRole: 2, checklist: mockUser.account.checklist },
    })));
    
    it('should test behavior with userRole equal to 2', () => {
        // your test here 
    });
    
    it('here we update mock implementation and test behavior with userRole equal to 1', () => {
        jwt_decode.mockImplementationOnce(() => ({
            data: { userRole: 1, checklist: mockUser.account.checklist },
        }));
        // your test here
    });
    
    it('since we used mockImplementationOnce method in the test above, here we again will be using initial mock implementation - userRole equal to 2', () => {
        // your test here
    });
    

    【讨论】:

    • 您好,感谢您的回复,但是,这会引发 jwt_decode.mockImplementationOnce 不是函数的错误。
    • 哦,对不起,我的错,我没有在jest.fn 中包装导出的函数。 jest.mock 只是模拟模块本身,但我们还需要模拟从模块导出的函数,以便有机会在每个测试中覆盖它的实现。我已经更新了答案,现在应该可以了。如果没有,请告诉我
    • 您好,我正在尝试实现类似的目标并收到jwt_decode.mockImplementationOnce 错误,即使您更新了答案。
    • 和上面jwt_decode.mockImplementationOnce is not a function一样的错误。我能够通过以不同的方式模拟它来解决这个问题。
    • @Samantha 您能否发送一个链接到某个沙箱以重现该问题,或者至少发送到带有代码的 github。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    相关资源
    最近更新 更多