5
votes

For test purposes I need to mock jwt-decode library. I use it as follows:

const decodedToken: { exp: number } = jwt_decode(token);

And then in tests tried the following and got errors like below:

jest.mock('jwt-decode');

TypeError: Cannot read property 'exp' of undefined

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

TypeError: (0 , _jwtDecode.default) is not a function

2
Related to stackoverflow.com/q/47056694/7470360 (but I don't think it's a duplicate).A Jar of Clay

2 Answers

11
votes

The issue is with the second argument of jest.mock. In your example, it is a function that returns an object:

jest.mock('jwt-decode', () => ({ ... }))

but as the property you are trying to mock is the default export of the module, the argument needs to be a function that returns a function that returns an object:

jest.mock('jwt-decode', () => () => ({ ... }))
-2
votes

The previous suggested solution of using it like this:

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

doesn't work - it throws an error:

 InvalidTokenError: Invalid token specified: Cannot read property 'replace' of undefined

Has anyone run into this issue as well and knows how to solve it?