【问题标题】:Jest manual mock doesn't return correct valueJest 手动模拟没有返回正确的值
【发布时间】:2016-09-14 12:49:10
【问题描述】:

升级到 15.1.1(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 是一个数组,所以您的意思是将push result 分配给_resultDeOuf 而不是分配给result 这是一个对象?
  • 其实这个 mock 不只返回数组

标签: javascript reactjs mocking jestjs manual


【解决方案1】:

我通过在窗口对象中设置 _resultDeOuf 来修复它。它很丑,但它有效

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    • 2014-11-26
    • 1970-01-01
    • 2023-03-24
    相关资源
    最近更新 更多