集成测试-redux / react + nock.js

时间:2018-10-15 14:15:06

标签: reactjs testing redux nock

我不知道如何找到编写此集成测试的方法。 我正在用酶来模拟反应组件,开玩笑地进行测试,用诺克来模拟axios api调用。

到目前为止,我创建了一个模拟点击按钮的测试,我想模拟api调用。

在互联网上没有太多帮助。

我的测试:

 it('Should invoke clear action and clear the group', (done) => {
    // GIVEN
    const clearButtonComponent = wrapper.find('[id="123"]');
    nock('http://localhost:8080')
      .intercept('/path/api/brum/123/group', 'DELETE')
      .reply(200, {
        status: 200,
        message: 'cleared',
      });
    const service = new myService();

    // WHEN
    clearButtonComponent.first().simulate('click');
    const result = Promise.resolve(service.clearGroup(123));

    // THEN
    expect(result).toEqual({ x: 'x' }); // I know it's not what I expect
    wrapper.update();
    done(); 
  });

异步操作redux:

export const clearGroup = id=> (dispatch, getState) => {
  myService.clearGroup(id)
    .then(() => {
        return dispatch(getGroup(id))
    });
};

myService中的方法:

  clearGroup(id) {
    return this._delete(`/${id}/group`);
  }

当然,路径更复杂,但是我的服务扩展了具有此基本URL的基本服务。

有人可以告诉我如何模拟它以使代码更进一步吗?

它仍然抱怨id是未定义的-看起来nock没有嘲笑它。

1 个答案:

答案 0 :(得分:1)

我会放弃nock(这些天我只尝试将其用于测试客户端),并开玩笑地嘲笑myService

我不使用axios,所以没有使用过它,但是它可以解决问题。.https://github.com/knee-cola/jest-mock-axios

否则,您可以考虑编写自己的模拟。.https://jestjs.io/docs/en/es6-class-mocks