lundi 10 août 2020

Mocking a module with Nested Functions with Jest

I have a module I am mocking like below, and I want to change the value of what create returns per test.

jest.mock('UserModule', () => {
  return {
    User: jest.fn().mockImplementation(() => {
      return {
        profile: {
          create: jest.fn().mockImplementation(() =>
            Promise.resolve({
              json: () => Promise.resolve({ test: 'ok' }),
              ok: true,
            })
          ),
        },
      }
    }),
  }
})

This would be called like new UserModule.User() and the calling profile.create() on that.

How can I make this so that I can switch the create implementation on the fly per test? This works for one test if I declare it outside of describe and I'm not sure how to switch this on the fly inside.

I tried putting the entire mock into each test, but that didn't work, in that case it appeared as if the function wasn't mocked at all.

  it('Should return true is response is ok', async () => {
      const response = await call('1234')
  })

Note: my call function above imports UserModule and calls

let userLib = new UserModule.User()
let response = await userLib.profile.create()

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire