无法在Jest中模拟jwt解码



出于测试目的,我需要模拟jwt解码函数,但我在这里找到的建议都没有帮助。使用jwtDecode的代码看起来像这个

import jwtDecode from 'jwt-decode';
...
const { exp } = jwtDecode(accessToken);

在测试中,我需要模拟这个返回的exp值。我试着按照Jest 中Mock jwt解码中的建议来嘲笑它

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

但这会返回

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

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

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

jest.mock('jwt-decode', () => jest.fn());

模拟测试中的值,例如:

(jwtDecode as jest.Mock).mockImplementationOnce(() => ({ exp: 12345 }));

要添加到@justenau答案中,如果不使用typescript,我们可以模拟单个测试中的导入,如下所示:

import jwtDecode from 'jwt-decode';
// do a generic mock at the top of your file:
jest.mock('jwt-decode', () => jest.fn());
// then somewhere inside your test
jwtDecode.mockImplementationOnce(() => ({ exp: 12345 }));
OR
jwtDecode.mockReturnValueOnce(() => ({ exp: 12345 }));

最新更新