我有一个问题,就是如何使用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();
如果com
是在communicatorAssist.js文件中的全局级别实例化的:它与communication.getData一起失败并不是函数错误。
但是,如果我在retrieveData()
函数中设置实例化,Andreas片段工作就可以了:
import communication from '../communication'
jest.mock('../communication', () => jest.fn());
communication.mockImplementation(
() => ({
getData: (success, error) => success()
})
)
(jest.mock()
工厂参数需要返回一个函数,而不是直接返回jest.fn
)
我不知道为什么它不能使用文件全局范围实例。
发布于 2017-09-30 09:23:38
您需要使用jest.fn()
来模拟模块,然后您可以导入它并使用mockImplementation
改变它的行为。
import communication from '../communication'
jest.mock('../communication', jest.fn());
communication.mockImplementation(
() => ({
getData: (success, error) => success()
})
)
https://stackoverflow.com/questions/46500749
复制相似问题