无法在 Jest 中模拟 jwt-decode

jus*_*nau 0 testing mocking typescript ts-jest

出于测试目的,我需要模拟 jwt-decode 函数,但我在这里找到的建议都没有帮助。使用 jwtDecode 的代码如下所示

 import jwtDecode from 'jwt-decode';
 ...
 const { exp } = jwtDecode(accessToken);
Run Code Online (Sandbox Code Playgroud)

在测试中我需要模拟这个返回exp值。我尝试按照Mock jwt-decode in Jest中的建议来模拟它

jest.mock('jwt-decode', () => () => ({ exp: 123456 }));
const { exp } = jwtDecode('123456');
Run Code Online (Sandbox Code Playgroud)

但这会返回

InvalidTokenError:指定的令牌无效:无法读取未定义的属性“替换”

jus*_*nau 5

对于那些也遇到这个问题的人 - 找到了解决它的方法。

将此行添加到文件顶部(在测试套件定义之前)

jest.mock('jwt-decode', () => jest.fn());
Run Code Online (Sandbox Code Playgroud)

模拟测试中的值如下所示:

(jwtDecode as jest.Mock).mockImplementationOnce(() => ({ exp: 12345 }));
Run Code Online (Sandbox Code Playgroud)