开玩笑的嘲笑实现

时间:2019-10-11 15:10:51

标签: node.js mocking jestjs

我一定不能正确理解某些内容。 根据阅读文档和我在网上看到的一些示例。我正在这样做:

// utils/handleError.js
export default () => {
  return {
    status: 'error'
  }
}
// utils/index.js
export { default as handleError } from './handleError'
...
// auth.js
import { handleError } from './utils'
export default async (key) => {
  if (!key) {
    return handleError()
  }
  ...
  // more async stuff here
}
// auth.test.js
import auth from './auth'
import { handleError } from './utils'

// also tried importing it directly
// import handleError from './utils/handleError'

jest.mock('./utils')

describe('Auth', () => {
  it('should error when no key present', async () => {
    handleError.mockImplementation(() => Promise.resolve({ status: 'check'})
    const res = await auth(false)
    expect(auth.status).toBe('check')
  })
})

我知道_.handleError.default.mockImplementation不是一个函数。 我的目标是最终更改每个测试的handleError的返回值。 (我知道这是一个不好的例子,handleError可能永远不会改变。这里我仅以它为例)

当我明确嘲笑每个fn

jest.mock('./utils', () => ({
  handleError: () => ({ status: 'poop' })
}))

像这样,它可以按预期工作,但是更改每个测试的返回值会与mockImplementationOnce()之类的链相混淆。

我在这里误解了什么?测试handleError时,应该如何正确模拟auth及其返回?

谢谢大家!

1 个答案:

答案 0 :(得分:0)

模拟每个测试的handleError返回值是正确的。

您可以使用语法糖功能mockFn.mockResolvedValueOnce(value)来代替mockImplementationOnce来进行快速模拟。

相关问题