17

在下面放一个小片段:

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 属性,因为它不是函数;给定的未定义

4

1 回答 1

9

您可以像这样模拟模块:

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')
  }
})

于 2019-03-06T08:14:58.410 回答