【问题标题】:How to test default exported javascript module in Jest?如何在 Jest 中测试默认导出的 javascript 模块?
【发布时间】:2020-05-21 03:52:59
【问题描述】:

我有一个 module.js 文件,内容如下

export default {
    foo(),
    bar()
}

我已经尝试在我的测试文件上这样做

jest.mock('/module/path', () => {
  foo: jest.fn().mockReturnValue(true)
})

import Module from './module/path'

这是我正在尝试做的测试

  test('test the module', () => {
    let fooSpy= jest.spyOn(Module, 'foo')

    vm.methodThatUseFoo()

    expect(fooSpy).toBeCalled()
  })

这是我遇到的错误

Cannot spyOn on a primitive value; undefined given

【问题讨论】:

    标签: javascript unit-testing vue.js jestjs


    【解决方案1】:

    此语法无法按预期工作:

    jest.mock('/module/path', () => {
      foo: jest.fn().mockReturnValue(true)
    })
    

    箭头函数返回undefined,因为foolabel

    隐式返回应该被解析为一个对象:

    jest.mock('/module/path', () => ({
      foo: jest.fn().mockReturnValue(true)
    }))
    

    或者考虑到它是默认导出,它更可能应该是:

    jest.mock('/module/path', () => ({
      default: {
        foo: jest.fn().mockReturnValue(true)
      }
    }))
    

    【讨论】:

    • 我已经尝试过你的建议,但不幸的是它仍然是错误,但错误是不同的,Cannot spy the foo property because it is not a function; undefined given instead,有什么建议吗?
    • 该错误表明可能是错误的。您需要始终使用默认导出。确保在测试代码中使用原始模块作为默认导入,使用default 键模拟它。您不需要监视它,因为 jest.mock 已经使 Module.default.foo 成为间谍。
    • 对不起,我还是不明白,如果 jest.mock 已经使它成为间谍,那么我如何测试 foo 是否被调用?我试过expect(Module.foo).toBeCalled() 但它不起作用
    • 这种情况下的错误是什么?至少从您发布的内容来看,它是 Module.default.foo,而不是 Module.foo。
    • 间谍似乎不起作用,错误是:expect(jest.fn()).toBeCalled() Expected number of calls: >= 1 Received number of calls: 0
    猜你喜欢
    • 1970-01-01
    • 2020-03-16
    • 2021-12-28
    • 1970-01-01
    • 2017-05-08
    • 2021-04-08
    • 1970-01-01
    • 2022-11-11
    • 2020-06-05
    相关资源
    最近更新 更多