Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从模拟模块模拟多个值?_Javascript_Reactjs_Jestjs - Fatal编程技术网

Javascript 如何从模拟模块模拟多个值?

Javascript 如何从模拟模块模拟多个值?,javascript,reactjs,jestjs,Javascript,Reactjs,Jestjs,我正在尝试模拟模块“jwt decode”,我可以使用以下方法成功模拟一个返回值: jest.mock('jwt-decode', () => () => ({ data: { userRole: 2, checklist: mockUser.account.checklist }})) 这适用于需要解码的jwt生成2的userRole的一个测试。然而,我的下一个测试需要userRole是一个角色,这就是问题所在 是否有一种正确的方法可以将userRole作为2返回给测试的第一个

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

 jest.mock('jwt-decode', () => () => ({ data: { userRole: 2, checklist: mockUser.account.checklist }}))
这适用于需要解码的jwt生成2的userRole的一个测试。然而,我的下一个测试需要userRole是一个角色,这就是问题所在


是否有一种正确的方法可以将userRole作为2返回给测试的第一个实例,1返回给测试的下一个实例?

您可以通过在模拟函数上调用
mockImplementation
mockImplementationOnce
来更改每个测试模拟函数的模拟实现,并将新实现作为参数,详情如下:

在您的情况下,可能是这样的:

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
仅模拟模块本身,但我们还需要模拟从模块导出的函数,以便有机会覆盖每个测试的it实现。我已经更新了答案,现在应该可以了。如果没有,请告诉我,我正在尝试实现类似的目标,并收到
jwt_decode.mockImplementationOnce
错误,即使您更新了答案。@Samantha错误是什么?与上述
jwt_decode.mockImplementationOnce相同的错误不是函数。我可以通过不同的模仿来解决这个问题。