【问题标题】:How to spy on a function that is imported in jest如何监视以 jest 形式导入的函数
【发布时间】:2019-07-27 14:58:36
【问题描述】:

在下面放一个小sn-p:

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

【问题讨论】:

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


    【解决方案1】:

    你可以像这样模拟模块:

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

    【讨论】:

    • 感谢您提出 TypeError: (0 , _xyz2.default)(...).catch is not a function with the first approach @andreas
    • 另外,为什么我不能断言 xyz 在计算测试中被调用?
    • 啊,抱歉我忽略了catch 部分,将更新我的答案
    • 如果你要模拟导入类的功能,你会怎么做?
    • 我认为这不能回答问题,OP 想知道他们如何监视函数,而答案却模拟了函数。我可能是错的,但是如果你监视你保留函数的实现,如果你模拟你删除它。
    猜你喜欢
    • 2019-06-12
    • 2018-11-24
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    相关资源
    最近更新 更多