用Jest模拟带有嵌套函数的模块

时间:2020-08-11 01:36:04

标签: javascript testing jestjs es6-modules

我有一个像下面这样嘲笑的模块,我想更改每个测试的create返回值。

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

这将被称为new UserModule.User(),并在其上调用profile.create()

如何做到这一点,以便可以在每次测试时即时切换create实现?如果我在describe以外声明它,则该方法适用于一个测试,并且不确定如何在内部动态切换它。

我尝试将整个模拟程序放入每个测试中,但这没有用,在这种情况下,似乎好像根本没有模拟该函数。

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

注意:我上面的调用函数会导入UserModule并进行调用

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

谢谢!

0 个答案:

没有答案
相关问题