Search code examples
javascripttypescripttestingjestjsauth0

Jest - how to use mocked class instance


In my frontend React application, I am using auth0-js library for authentication. It exports WebAuth class. In the code, I create an instance by calling WebAuth Something like this:

import { WebAuth } from 'auth0-js'


const auth0Client = new WebAuth({ /* some options */ })

/* 
...
using auth0Client
...
*/

I've create a file called just like the name of the library in my __mocks__ folder. Thanks to that, Jest automatically mocked this library.

// __mocks__/auth0-js.ts
const auth0Mock = jest.genMockFromModule('auth0-js')

module.exports = auth0Mock

But, in my tests I want to check whether some method on auth0Client was invoked. How can I do this?


Solution

  • Here is a simple working example to get you started:

    __mocks__/auth0-js.ts

    module.exports = jest.genMockFromModule('auth0-js')
    

    code.ts

    import { WebAuth } from 'auth0-js'
    
    const auth0Client = new WebAuth({ domain: 'your domain', clientID: 'your client id'});
    auth0Client.authorize({ audience: 'your audience' });
    

    code.test.ts

    import { WebAuth } from 'auth0-js';
    import './code';  // <= run code.ts
    
    test('code', () => {
      expect(WebAuth).toHaveBeenCalledWith({ domain: 'your domain', clientID: 'your client id' });  // Success!
      const auth0Client = (WebAuth as jest.Mock).mock.instances[0];  // <= get the WebAuth instance
      expect(auth0Client.authorize).toHaveBeenCalledWith({ audience: 'your audience' });  // Success!
    })
    

    WebAuth is a mock function so when it is used to create a new instance it will record the instance it created.

    During the test you can retrieve WebAuth and use it to retrieve the instance that was created.

    Once you have the instance, you can check its functions (also mock functions) to see if they were called as expected.