首页 > 解决方案 > 如何在我的反应项目中使用“酶”和“笑话”测试使用“超级代理”的异步操作?

问题描述

我是项目测试部分的新手。

我的个人项目有问题。我使用“superagent”从 Api 获取信息,现在我想为它编写测试。但我不能使用 Enzyme 示例中使用的 'fetch-mock' 包。

这是我的动作文件。

   // getRecommendedProductsActions.js

    import request from 'superagent';

    export const getRecommendedProducts = () => (dispatch) => {
      dispatch(fetchProducts());
      return request
        .get(URL_PRODUCT_BASE)
        .set('Content-Type', 'application/json')
        .then(res => dispatch(receiveProducts(res.body)))
        .catch(err => dispatch(receiveFailure(err)));
    };

这是我的测试文件。

// test/getRecommendedProducts.test.js

import configureMockStore from 'redux-mock-store';
import fetchMock from 'fetch-mock';
import thunk from 'redux-thunk';
import { getRecommendedProducts } from '../../src/actions/products';

describe('async actions', () => {
  afterEach(() => {
    fetchMock.reset();
    fetchMock.restore();
  });

  it('creates RECEIVE_PRODUCTS when fetching products has been done', () => {
    fetchMock
      .get('/products', {
        body: httpBody,
        headers: { 'content-type': 'application/json' },
      });

    const expectedActions = successResponse;

    const store = mockStore();

    return store.dispatch(getRecommendedProducts())
      .then(() => expect(store.getActions()).toEqual(expectedActions));
  });

而且我发现“superagent”不是基于 fetch 的,“fetch-mock”不起作用。我也找到了一个__mocks__/superagent.js文件。

// mock for superagent - __mocks__/superagent.js

let mockDelay;
let mockError;
let mockResponse = {
  status() {
    return 200;
  },
  ok() {
    return true;
  },
  body: {
    walla: true,
  },
  get: jest.fn(),
  toError: jest.fn(),
};

const Request = {
  post() {
    return this;
  },
  get() {
    return this;
  },
  send() {
    return this;
  },
  query() {
    return this;
  },
  field() {
    return this;
  },
  set() {
    return this;
  },
  accept() {
    return this;
  },
  timeout() {
    return this;
  },
  end: jest.fn().mockImplementation(function (callback) {
    if (mockDelay) {
      this.delayTimer = setTimeout(callback, 0, mockError, mockResponse);

      return;
    }

    callback(mockError, mockResponse);
  }),
  // expose helper methods for tests to set
  __setMockDelay(boolValue) {
    mockDelay = boolValue;
  },
  __setMockResponse(mockRes) {
    mockResponse = mockRes;
  },
  __setMockError(mockErr) {
    mockError = mockErr;
  },
};

module.exports = Request;

感谢你们的所有帮助。

标签: reactjstestingenzymesuperagent

解决方案


推荐阅读