首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用Jest模拟ES6类函数

用Jest模拟ES6类函数
EN

Stack Overflow用户
提问于 2017-09-30 07:54:08
回答 1查看 23.1K关注 0票数 17

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

这是用例的一个简化示例:

代码语言:javascript
运行
复制
// 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()函数的行为更改为调用successerror回调,而不调用post方法。

我只成功地模拟了整个测试文件的getData()函数,其中最上面的片段是:

代码语言:javascript
运行
复制
import communication from '../communication'
jest.mock('../communication', () => (() => ({
    getData: (success, error) => success()
})));

但我不能在不同测试用例的实现之间切换。

我认为使用.mockImplementation()的东西可以做到这一点,但在我的例子中我无法做到这一点(我看到了一些例子,将它用于模块导出函数,而不是用于类)。

有谁有主意吗?

编辑

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

代码语言:javascript
运行
复制
const com = new communication();

如果com是在communicatorAssist.js文件中的全局级别实例化的:它与communication.getData一起失败并不是函数错误。

但是,如果我在retrieveData()函数中设置实例化,Andreas片段工作就可以了:

代码语言:javascript
运行
复制
import communication from '../communication'
jest.mock('../communication', () => jest.fn());

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

(jest.mock()工厂参数需要返回一个函数,而不是直接返回jest.fn)

我不知道为什么它不能使用文件全局范围实例。

EN

回答 1

Stack Overflow用户

发布于 2017-09-30 09:23:38

您需要使用jest.fn()来模拟模块,然后您可以导入它并使用mockImplementation改变它的行为。

代码语言:javascript
运行
复制
import communication from '../communication'
jest.mock('../communication', jest.fn());

communication.mockImplementation(
  () => ({
    getData: (success, error) => success()
  })
)
票数 17
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46500749

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档