Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock jwt-decode in Jest

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

like image 531
heisenberg7584 Avatar asked Feb 25 '20 13:02

heisenberg7584


1 Answers

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', () => () => ({ ... }))
like image 171
A Jar of Clay Avatar answered Nov 04 '22 19:11

A Jar of Clay