【问题标题】:Code coverage not working for Jest test with Axios代码覆盖率不适用于 Axios 的 Jest 测试
【发布时间】:2020-05-09 13:52:13
【问题描述】:

我正在使用Jestmoxios 为我的异步函数编写测试:

export function getData(id) {
  return dispatch => {
    return axios({
      method: "get",
      url: `${'url'}/id`
    })
      .then(response => {
        dispatch(setData(response.data));
      })
      .catch(() => alert('Could not fetch data');
  };
}

测试:

import configureMockStore from "redux-mock-store";
import thunk from "redux-thunk";
import moxios from "moxios";
import getData from '../redux/getData';

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
const store = mockStore({});

describe('Test fetch data', () => {
  beforeEach(function() {
    moxios.install();
    store.clearActions();
  });
  afterEach(function() {
    moxios.uninstall();
  });
  it('should fetch data and set it', () => {
         const data = [{ name: 'John', profession: 'developer'}];
         moxios.wait(() => {
         const request = moxios.requests.mostRecent();
         request.respondWith({
           status: 200,
           response: data
         });
        const expectedActions = [setData(data)];
        return store.dispatch(getData()).then(() => {
        expect(store.getActions()).toEqual(expectedActions);
      });
    });
  })
})

我的测试通过了,但是当我检查 Jest 生成的代码覆盖率报告时,它显示 getDatathen 块没有被覆盖/调用。我该如何解决这个问题?

【问题讨论】:

  • 它是给你一个错误还是什么都没有?顺便说一句,check this question 可能对你有帮助:)

标签: javascript jestjs moxios


【解决方案1】:

moxios.wait return Promise 你的测试函数在运行 except 函数之前返回。

你需要在你的测试函数中使用done回调

it('should fetch data and set it', (done) => {
    const data = [{
        name: 'John',
        profession: 'developer'
    }];
    moxios.wait(() => {
        const request = moxios.requests.mostRecent();
        request.respondWith({
            status: 200,
            response: data
        });
        const expectedActions = [setData(data)];
        store.dispatch(getData()).then(() => {
            expect(store.getActions()).toEqual(expectedActions);
            done();
        });
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-31
    • 2010-10-16
    • 2019-06-11
    • 1970-01-01
    • 2020-06-03
    • 2012-01-18
    • 2023-03-04
    • 1970-01-01
    相关资源
    最近更新 更多