Javascript 用Jest模拟ES6类函数

Javascript 用Jest模拟ES6类函数,javascript,unit-testing,react-redux,jestjs,Javascript,Unit Testing,React Redux,Jestjs,我有一个问题,关于如何使用Jest模拟ES6类实例,Jest是我实际想要测试的方法所使用的。 我的真实案例是尝试测试一个Redux异步操作创建者,该创建者发出请求并根据请求结果分派一些操作 这是用例的简化示例: // communication.js // An exported ES6 class module with proxy to the request library. import post from './post'; export default class communica

我有一个问题,关于如何使用Jest模拟ES6类实例,Jest是我实际想要测试的方法所使用的。 我的真实案例是尝试测试一个Redux异步操作创建者,该创建者发出请求并根据请求结果分派一些操作

这是用例的简化示例:

// communication.js
// An exported ES6 class module with proxy to the request library.
import post from './post';
export default class communication {

    getData(data, success, error) {
        const res = post(data);
        if(res) {
            success();
        } else {
            error();
        }
    }
}

// communicatorAssist.js
// A redux async function using communication.js
import communication from './communication';
// ...

export function retrieveData() {
    return dispatch => {
        const data = { name: 'michel'};
        communication.getData(data,
            (res) => dispatch(successAction(res)),
            (res) => dispatch(errorAction(res));
    }
}

// communicatorAssist.test.js testing the communicatorAssist
import { retrieveData } from 'communicatorAssist';

// communication.getData should call success callback
// for this test.
it('Should call the success callback', () => {
    retrieveData();
    // Assert that mocked redux store contains actions
});

// communication.getData should call error callback
// for this test.
it('Should call the error callback', () => {
    retrieveData();
    // Assert that mocked redux store contains actions
});
我想要的是在测试中模拟通信类,并在每个测试中将
getData()
函数的行为更改为调用
success
error
回调,而不调用任何post方法

我只成功地模拟了整个测试文件的
getData()
函数,其顶部有以下代码段:

import communication from '../communication'
jest.mock('../communication', () => (() => ({
    getData: (success, error) => success()
})));
但我不能在不同的测试用例中切换实现

我认为使用
.mockImplementation()
可以做到这一点,但在我的案例中,我无法做到这一点(我看到一些示例将其用于模块导出函数,但不用于类)

有人有主意吗

编辑

我忘记了代码示例中的一部分:通信类实例创建,我认为这是模拟它的“问题”:

const com = new communication();
如果在communicatorAssist.js文件中在全局级别实例化了
com
:则会因通信而失败。getData不是函数错误

但是,如果我在
retrieveData()函数中设置实例化,Andreas Köberle代码片段就可以了:

import communication from '../communication'
jest.mock('../communication', () => jest.fn());

communication.mockImplementation(
  () => ({
    getData: (success, error) => success()
  })
)
jest.mock()
工厂参数需要不直接返回函数
jest.fn


我不知道为什么它不能使用文件全局作用域实例工作。

您需要使用
jest.fn()
模拟模块,然后您可以导入它并使用以下方法更改其行为:


我已经用你的答案编辑了这个问题,如果通信类在retrieveData函数中实例化,效果会很好。如果getData的结果在这个测试文件中的不同测试中有所不同,该怎么办?@Marc然后你创建了各种不同的通信模拟,每个模拟都有自己的模拟getData函数。第2行产生以下错误
jest.mock'的第二个参数必须是内联函数
import communication from '../communication'
jest.mock('../communication', jest.fn());

communication.mockImplementation(
  () => ({
    getData: (success, error) => success()
  })
)