Jauny
Jauny

Reputation: 970

Jest mock class instance function

I have a scenario that seems pretty straight forward but I'm not able to find an example in the doc that does what I need. I've searched SO also but haven't found anything apparently...

I want to mock a function from a class that is initialised and used inside the function I'm actually testing.

Here's an example:

// helpers.js
import API from './api'

export const validateUsername = async (username) => {
  const myApi = new API()
  try {
    await myApi.validate(username)
    return 'valid'
  } catch (e) {
    return 'invalid'
  }
}

In my test, I want to mock myApi.validate to make it return a valid response or throw. But for some reason I can't find the way to do it.

// helpers-test.js
it('returns "invalid" if the username is invalid', async () => {
  // here I need to mock myApi.validate to return or throw
})

I'm really not sure why I haven't figured this out yet, seems pretty common to do right?

Anyone?

Upvotes: 1

Views: 467

Answers (1)

Jauny
Jauny

Reputation: 970

So I figured it out thanks to @Volodymyr.

I think my main issue was to import the lib before mocking it.

jest.mock('path/to/api')
import {Api} from 'path/to/api'

const validateMock = jest.fn().mockImplementation(() => {...})
Api.prototype.validate = validateMock

// now it works

Upvotes: 1

Related Questions