javascript - Jest 手动模拟未返回正确的值

标签 javascript reactjs mocking jestjs manual

升级到 15.1.1 后,我遇到了开 Jest 手动模拟的问题(react 是 15.3.1)

当我在测试中设置模拟结果时,当调用模拟方法时,实际结果不是预期的结果,而是创建变量时的初始结果。

在我升级 React 和 Jest 之前,它工作得很好。

这是我的模拟:

'use strict';

const psMock = jest.genMockFromModule('../ProcessService');
import clone from 'lodash/clone'

var _resultDeOuf = [];

function __setMockResult(result) {
    _resultDeOuf = result;
}

psMock.getRelatedProcessesByGroupingId = jest.fn(() => {
    return {
        then: (callback) => callback(_resultDeOuf);
    }
});

psMock.__setMockResult = __setMockResult;

export default psMock`

这是我的测试:

jest.unmock('../SuperProcessRow');
jest.unmock('../ProcessRow');

import React from "react";
import ReactDom from "react-dom";
import TestUtils from "react-addons-test-utils";
import processService from 'ProcessService'

import SuperProcessRow from '../SuperProcessRow'

const defaultSuperProcess = {
    "processId": "97816",
    "executionId": null,
    "cancelExecutionId": null
}

describe('SuperProcessRow', () => {

    beforeEach(() => {
        processService.getRelatedProcessesByGroupingId.mockClear()
    });

    it('load sub processes on super process click ', () => {

        let responseSubProcesses = {
            processes : subProcesses,
            totalCount : 5
        };

        processService.__setMockResult(responseSubProcesses);

        let superProcessRow = TestUtils.renderIntoDocument(
        <table><SuperProcessRow process={defaultSuperProcess}/></table>);

        superProcessRow = ReactDom.findDOMNode(superProcessRow);

        let icon = superProcessRow.querySelector('i');
        TestUtils.Simulate.click(icon);

        expect(processService.getRelatedProcessesByGroupingId.mock.calls.length).toEqual(1);
    })
});

在实际的生产代码中,我调用了 getRelatedProcessGroupingId 并在 .then 方法内处理响应。我没有检索测试中的数据集,而是得到了初始值:[]。

有人有想法吗?

谢谢 文森特

最佳答案

我通过在窗口对象内设置 _resultDeOuf 来修复它。虽然很丑,但是很管用

关于javascript - Jest 手动模拟未返回正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39490881/

相关文章:

javascript - 如何用html和js制作无限 map

javascript - 我如何将所选项目从 React Native Paper Menu 传递到 Input/TextInput onChangeText 行为

java - JUnit 比较集合中的对象,但包含对象中的指定字段除外

javascript - React Meteor、reactive prop 和内部状态

javascript - React 函数组件父状态更改不会重新渲染子组件

python - 如何在测试中为多个函数重用相同的模拟

Python 模拟方法调用参数显示列表的最后状态

javascript - 如何在不实际最小化浏览器窗口的情况下在全屏桌面 View 上显示 react.js 组件的 css 移动 View 分辨率?

javascript - 在表单提交之前用 AngularJS 同步调用服务器

css - 如何在 React 中将多个浏览器特定值添加到 CSS 样式中?