redux-observable unit test epci with dependencies

时间:2017-08-16 05:53:59

标签: unit-testing jest redux-observable

我有一个带有以下签名的史诗(注意依赖性)

export const incrementalSearchEpic = (action$, store, { incrementalSearchService }) => {
    // eslint-disable-next-line max-len
    return action$.ofType('SEARCH_STORES').mergeMap((action) =>
        incrementalSearchService.performIncrementalSearch(action)
    );
};

现在我需要对此进行单元测试,这是我的单元测试代码

beforeEach(() => {
    epicMiddleWare = createEpicMiddleware(incrementalSearchEpic,
        {
            dependencies: {
                incrementalSearchService: IncrementalSearchServiceMock
            }
        });
    const mockStore = configureMockStore([epicMiddleWare]);
    const getState = {}; // initial state of the store         
    store = mockStore(getState);
});

// eslint-disable-next-line max-len
it('calls the incrementalSearchService->performIncrementalSearch with the parameters when called', () => {
    //dispatch the incremental search action
    const searchStore = {
        type: 'SEARCH_STORES',
        SearchText: 'Aldi'
    };

    store.dispatch(searchStore);

    expect(store.getActions()).toEqual([
        searchStore
    ]);
});

然而,当我运行代码时,我收到以下错误

TypeError:无法读取属性' performIncrementalSearch'未定义的

似乎依赖关系没有正确传递。

1 个答案:

答案 0 :(得分:0)

我刚刚意识到:如果redux-observable没有注入提供的依赖项对象,那么你实际上得到的Cannot read property 'incrementalSearchService' of undefined不是performIncrementalSearch,因为redux-observable默认情况下不会注入一个对象 - 它不会出错,因为它是确实传递了你的对象。

相反,可能的问题是您IncrementalSearchServiceMock的导入或定义实际上是undefined。也许是一个错误的命名导入或类似。

如果您无法立即查明原因,请在beforeEach的开头暂停调试器,并确认IncrementalSearchServiceMock的值未定义。