1

我正在使用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 生成的代码覆盖率报告时,它显示该thengetData未被覆盖/调用。我怎样才能解决这个问题?

4

1 回答 1

0

moxios.wait在运行函数之前返回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();
        });
    });
});
于 2020-05-10T08:47:31.153 回答