首页 > 解决方案 > TypeError:ClassName.methodName 不是函数

问题描述

我正在嘲笑一个从节点模块导入的 ES6 类,如下所示:

// creating mocks
const mockMethodName = jest.fn()

jest.mock('../node_modules/my-module', () => {
    const actualMyModule = jest.requireActual('../node_modules/my-module')
    
    return {
        ...actualMyModule,
        ClassName: jest.fn().mockImplementation(() => {
            return {
                methodName: mockMethodName
            }
        })
    }
})

const { ClassName } = require('my-module')

// the test
it('does something successfully', () => {
    // test logic that triggers ClassName.methodName()

    expect(mockMethodName).toHaveBeenCalledTimes(1)
})

但我收到以下错误:

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function
without a catch block, or by rejecting a promise which was not handled with .catch().
The promise rejected with the reason 
"TypeError: ClassName.methodName is not a function".] {
  code: 'ERR_UNHANDLED_REJECTION'
}

我也尝试过像这样定义模拟方法:

const mockMethodName = jest.fn(() => {})
const mockMethodName = jest.fn(() => null)
const mockMethodName = jest.fn(() => true)
const mockMethodName = jest.fn(() => jest.fn)

但错误仍然存​​在。

我究竟做错了什么?如何正确模拟课堂?

PS:该ClassName.methodName()方法在异步函数中调用,但ClassName.methodName()不返回承诺

标签: javascriptnode.jstestingjestjs

解决方案


推荐阅读