【问题标题】:Javascript promises In React-Enzyme test not returning mocked valueJavascript 承诺在 React-Enzyme 测试中不返回模拟值
【发布时间】:2018-08-07 09:31:24
【问题描述】:

我正在尝试测试一个 React 组件,其中包含对 api 库的调用,因此返回了一个承诺。

api 库如下所示:(utils/api.js)

import axios from "axios";
import Q from "q";

export default {
    createTrip(trip) {
        return Q.when(axios.post("/trips/", trip));
    }
}

我已经模拟如下:(utils/__mocks__/api.js)

export default {
    createTrip(trip) {
        return new Promise((resolve, reject) => {
            let response = {status: 201, data: trip};
            resolve(response)
        })
    }
}

我正在测试的功能是:

create() {
    api.createTrip(this.state.trip).then(response => {
        if (response.status === 201) {
            this.setState({trip: {}, errors: []});
            this.props.onTripCreate(response.data);
        } else if (response.status === 400) {
            this.setState({errors: response.data})
        }
    });
}

测试是:

jest.mock('utils/api.js');
test('succesful trip create calls onTripCreate prop', () => {
    const trip = {'name': faker.random.word()};

    const spy = jest.fn();
    const container = shallow(<TripCreateContainer onTripCreate={spy}/>);

    container.setState({'trip': trip});
    container.instance().create();

    expect(spy).toHaveBeenCalledWith(trip);
    expect(container.state('trip')).toEqual({});
    expect(container.state('errors')).toEqual([]);
});

我相信这应该可行,但测试结果是:

succesful trip create calls onTripCreate prop

expect(jest.fn()).toHaveBeenCalledWith(expected)

Expected mock function to have been called with:
  [{"name": "copy"}]
But it was not called.

  at Object.test (src/Trips/__tests__/Containers/TripCreateContainer.jsx:74:21)
      at new Promise (<anonymous>)
  at Promise.resolve.then.el (node_modules/p-map/index.js:46:16)
      at <anonymous>

我不确定如何解决此测试,如果有人可以提供帮助,我将不胜感激?

【问题讨论】:

  • 您的测试中的trip 对象似乎只有name 属性。您需要传递 responseresponse.status 属性,因为它是从您的 Promise 解决的,并且您正在逻辑中检查它的值
  • 我已经编辑了代码,但仍然得到同样的错误@t3__rry
  • 好的,您也可以编辑您的问题
  • 我已经这样做了,我已经更改了模拟api.js文件@t3__rry

标签: javascript reactjs jestjs es6-promise enzyme


【解决方案1】:

你很接近。

then 将回调排队等待执行。回调在当前同步代码完成并且事件循环抓取接下来排队的任何内容时执行。

thencreate() 中排队的回调有机会运行之前,测试正在运行完成并失败。

给事件循环一个循环的机会,以便回调有机会执行,这应该可以解决问题。这可以通过使您的测试函数异步并等待您想要暂停测试并让任何排队的回调执行的已解决承诺来完成:

jest.mock('utils/api.js');
test('succesful trip create calls onTripCreate prop', async () => {
    const trip = {'name': faker.random.word()};

    const spy = jest.fn();
    const container = shallow(<TripCreateContainer onTripCreate={spy}/>);

    container.setState({'trip': trip});
    container.instance().create();

    // Pause the synchronous test here and let any queued callbacks execute
    await Promise.resolve();

    expect(spy).toHaveBeenCalledWith(trip);
    expect(container.state('trip')).toEqual({});
    expect(container.state('errors')).toEqual([]);
});

【讨论】:

  • 非常感谢,我没有意识到你可以等待没有实例
猜你喜欢
  • 2020-11-20
  • 1970-01-01
  • 1970-01-01
  • 2020-07-30
  • 2018-05-29
  • 1970-01-01
  • 2014-07-05
  • 2018-09-15
  • 2015-10-30
相关资源
最近更新 更多