javascript - 如何监视对于Jest方式导入的函数

标签 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 是 Jest 。我该怎么做 ?

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

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

这给了我以下错误:

Cannot spy the xyz property because it is not a function; undefined given instead

最佳答案

您可以像这样模拟模块:

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

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


如果您需要来自模拟的不同返回值,则需要模拟模块以便它返回一个 spy 。然后你必须导入模块,你可以在测试期间设置返回值:
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')
  }
})

关于javascript - 如何监视对于Jest方式导入的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55014727/

相关文章:

javascript - 如何测试@Input()项: any in Angular?

java - Powermockito - 无法模拟/监视系统类

vue.js - Vuex with Jest - this.$store.getters.<getterName> 不是函数

如果安装了 Flash Player,则重定向到另一个域的 Javascript 代码

javascript - 摆脱 AngularJS 项目中 ngTemplate 的使用

javascript - 使用Winston Logger登录/var/log失败

java - 将值设置为模拟对象但得到 null

javascript - 使用 Quasar-Framework 0.15 进行 Jest 单元测试配置

unit-testing - 类型错误 : Cannot read property 'contextTypes' of undefined

javascript - 将 jquery 选择器与变量相乘