如何监视开玩笑导入的功能

时间:2019-03-06 02:42:51

标签: javascript unit-testing jestjs jest-fetch-mock

在下面插入一个小片段:

import xyz from '../xyz'
function calculate() {
  return xyz(arg1, arg2).catch((err) => {
    func1()
    func2()
  })
}
export default calculate

我只是想断言xyz是在开玩笑。我该怎么做 ?

我尝试了以下操作,但不起作用:

import * as myModule from '../xyz'
import calculate from '../../calculate'
const mock = jest.spyOn(myModule, 'xyz')
mock.mockReturnValue('mocked value')
const op = calculate()
expect(op).toBe('mocked value')

这给了我以下错误:

  

因为它不是函数,所以无法监视xyz属性;未给定

1 个答案:

答案 0 :(得分:0)

您可以像这样模拟模块:

import calculate from '../../calculate'
jest.mock('../xyz', ()=> () => Promise.resolve('mocked value'))

it('does something', async()=>{
  const op = await calculate()
  expect(op).toBe('mocked value')
})

如果您需要与模拟不同的返回值,则需要模拟模块,以便它返回一个间谍。然后,您必须导入模块,然后可以在测试期间设置返回值:

import calculate from '../../calculate'
import myModule from '../xyz'
jest.mock('../xyz', ()=> jest.fn())

it('does something', async() => {
  myModule.mockImplementation(() => () =>  Promise.resolve('mocked value'))

  const op = calculate()
  expect(op).toBe('mocked value')
})

it('does something else', async() => {
  myModule.mockImplementation(() => () =>  Promise.resolve('another value'))
  const op = await calculate()
  expect(op).toBe('another value')
})


it('does fail', async() => {
  myModule.mockImplementation(() => () =>  Promise.reject('some Error')
  try{
    const op = await calculate()
  }catch (e){
    expect(e).toBe('some Error')
  }
})