0

For testing purposes I need to mock jwt-decode function but none of the suggestions I've found here helped. The code were jwtDecode is used looks like this

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

And inside the test I need to mock this returned exp value. I've tried mocking it as per suggestion found in Mock jwt-decode in Jest

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

But that returns

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

IAmCoder
  • 3,179
  • 2
  • 27
  • 49
justenau
  • 41
  • 1
  • 5

2 Answers2

4

For those who also run into this issue - found a way to solve it.

Add this line on the top of your file (before test suite definition)

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

And the mock the value inside tests f.e. like this:

(jwtDecode as jest.Mock).mockImplementationOnce(() => ({ exp: 12345 }));
justenau
  • 41
  • 1
  • 5
0

To add to @justenau answer, if not using typescript, we can mock the import inside individual tests like so:

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 }));
nishkaush
  • 1,512
  • 1
  • 13
  • 20