我的反应动作thunk jest

时间:2017-03-11 17:54:10

标签: unit-testing reactjs jestjs

我目前正在尝试测试我的thunk动作(getUserFeatureNames)以查看它是否使用jest调用成功动作(getUserFeatureNamesSuccess)。 getUserFeatureNames thunk动作当前驻留在loginActions.js文件中,这是导入homeQueries(我试图模拟)。到目前为止,我在运行我的jest测试时遇到以下错误..

TypeError:_homeQueries2.default.getFeatureNames不是函数

如何模拟homeQueries.getFeatureNames?

function createStore(state = {}, expectActions = {}){
  const mockStore = configureMockStore([thunk]);
  return mockStore(state, expectActions);
}

describe("home_async_tests", () => {

test("getUserFeatureNamesSuccess action is called if request was success", (done) => {

jest.mock('../../../graphQL/homeQueries', () => {
  return jest.fn(() => {
     {
      getFeatureNames: () =>{
          return new Promise((resolve, reject) => {
            let array = [{iconFile: 'Personalization.png', description: 'Personalization'},{iconFile: 'Home.png', description: 'Home'}];
            resolve(array);
          });
      };
    }
  });

});
jest.dontMock('../../../app/redux/actions/homeActions');
let homeActions = require('../../../app/redux/actions/homeActions');
const expectedAction = {type: types.userFeatureNamesSuccess, payLoad: {isError: false, data: '' }};
const store = createStore();
store.dispatch(homeActions.getUserFeatureNames({token:"fdis4554" })).then(() => {
  const actions = store.getActions();
  expect(actions[0].type).toEqual(expectedAction.type);
  expect(actions[0].payLoad.isError).toEqual(expectedAction.payLoad.isError);
  done();
});

});

1 个答案:

答案 0 :(得分:1)

我假设模块只返回一个对象,而不是一个返回一个对象的函数,所以你的模拟应该是这样的:

jest.mock('../../../graphQL/homeQueries', () = > ({
    getFeatureNames: () = > {
      return new Promise((resolve, reject) = > {
        let array = [{
          iconFile: 'Personalization.png',
          description: 'Personalization'
        }, {
          iconFile: 'Home.png',
          description: 'Home'
        }];
        resolve(array);
      });
    };
  }
});