首页 > 解决方案 > Mock.mockImplementation 不是函数

问题描述

我试图在这里搜索每一个类似的问题,不幸的是没有解决方案对我有用。

我目前正在尝试从一个模块模拟命名导出,如下所示:

模块.ts

export function someFunctionOne() {
    // implementation
}

export const someFunctionTwo = function (
) {
    // implementation
}

export const someFunctionThree = () => {
    // implementation
}

export const someFunctionFour = () => {
    // implementation
}

这里有四个导出,在我的测试中,我需要模拟整个模块:

测试如下所示:

模块.test.ts

import React from 'react'
import { shallow } from 'enzyme'
import Component from './component' // component I am testing
import { someFunctionOne, someFunctionTwo  } from './module'

;(jest as any).mock('./module', () => ({
    someFunctionOne: jest.fn(),
    someFunctionTwo: jest.fn(),
    someFunctionThree: jest.fn(() => 10),
    someFunctionFour: jest.fn((s) => s),
}))
;(someFunctionOne as any).mockReturnValue('some String')
;(someFunctionTwo as any).mockReturnValue(false)


describe('Component', () => {
    beforeEach(() => {
        ;(someFunctionOne as any).mockReset()
        ;(someFunctionTwo as any).mockReset()
    })
    it('renders', () => {
        ;(someFunctionOne as any).mockImplementationOnce(jest.fn(() => 'some string'))
        ;(someFunctionTwo as any).mockImplementationOnce(jest.fn(() => false))
        const shallowRenderedModule = shallow(
            <Module>
                <div>Children textContent here</div>
            </Module>
        )
        expect(shallowRenderedModule).toMatchSnapshot()
    })
    // Then, many other tests...
})

我也有jestbabel-jest配置为:

jest.config.js

module.exports = {
    displayName: 'redacted-app',
    setupFilesAfterEnv: ['./jest/jest.setup'],
    preset: '../../jest.preset.js',
    transform: {
        '^.+\\.[tj]sx?$': [
            'babel-jest',
            { cwd: __dirname, configFile: './babel-jest.config.json' },
        ],
        '\\.(svg)$': './jest/svg.transform',
    },
    moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
}

babel-jest.config.json

{
    "presets": [
        [
            "@babel/preset-env",
            {
                "targets": {
                    "node": "current"
                }
            }
        ],
        "@babel/preset-typescript",
        "@babel/preset-react"
    ]
}

问题是,无论我从Mock( mockImplementation,mockReturnValue等) 使用什么方法,我总是最终得到_moduleName.someFunctionOne.mockReturnValue is not a function

    TypeError: _moduleName.someFunctionOne.mockReturnValue is not a function

      10 |      someFunctionFour: jest.fn((s) => s),
      11 | }))
    > 12 | ;(someFunctionOne as any).mockReturnValue('some String')
         |                     ^
      13 | ;(someFunctionTwo as any).mockReturnValue(false)

console.log看来,出口实际上并没有被嘲笑。

我在这里不知所措,会是什么?我试过了:

但这些都不起作用。

标签: javascriptreactjstypescriptunit-testingjestjs

解决方案


我在 mockimplementation is not a function 方面遇到了类似的问题,只是意识到我忘记了 jest.setup.js 文件。

您可能已经检查过了,但是如果您在那里添加了模块,您是否查看了 jest.setup.js 而不是 jest.config.js (jest.mock('...'));

这为我解决了这个问题,因为我想模拟一项服务。可能是我很容易忽略的东西。


推荐阅读