我已经按照 Redux Sagas 的文档创建了一组测试,但它们对我来说似乎非常脆弱。每当我更新任何 sagas 中的逻辑时,我的测试都会失败。这在我的脑海中敲响了警钟,让我认为我做错了什么。
这是一个示例 saga,它与 API 通信以加载用户的配置文件并将其存储在 Redux 状态中:
export function* userAuthCheck() {
try {
yield put({ type: START_HTTP });
const me = yield apply(user, user.me);
const organisations = yield apply(user, user.organisations, [me.body.data.id]);
yield put({
type: USER_AUTH_SUCCESS,
redirect: true,
state: {
account: me.body.data,
organisations: organisations.body.data,
},
});
} catch (error) {
yield put({ type: USER_AUTH_REFRESH });
} finally {
yield put({ type: COMPLETE_HTTP });
}
}
这是相应的测试:
it('can successfully call the API', () => {
const generator = userAuthCheck();
expect(generator.next().value).toEqual(put({ type: START_HTTP }));
expect(generator.next().value).toEqual(call(user.me));
expect(generator.next().value).toEqual(put({
type: USER_AUTH_SUCCESS,
state: { user: undefined },
}));
expect(generator.next().value).toEqual(put({ type: COMPLETE_HTTP }));
});
您可能会注意到,如果运行测试实际上会失败,因为自从我最近对 saga 进行了一些更新后我还没有更新它。这就是让我走上这条思路的事情。
有没有更好的方法来测试我的 sagas?是否可以从头到尾运行它们,模拟不同的 API 响应并断言将正确的事情分派(dispatch)到状态?
这些是我一直关注的文档:https://redux-saga.github.io/redux-saga/docs/introduction/BeginnerTutorial.html
最佳答案
我喜欢通过模拟商店来测试它,所以对于您的示例,它类似于:
import configureMockStore from "redux-mock-store";
import createSagaMiddleware from "redux-saga";
import rootSaga from "pathToRootSaga/rootSaga";
import {userAuthCheckActionCreator} from "yourPath/UserActionCreators";
it('can successfully call the API', () => {
const sagaMiddleware = createSagaMiddleware();
const mockStore = configureMockStore([sagaMiddleware]);
const store = mockStore({});
sagaMiddleware.run(rootSaga);
const expectedActions = [
{
type: START_HTTP
},
{
type: USER_AUTH_SUCCESS,
redirect: true,
state: {
account: me.body.data,
organisations: organisations.body.data,
}
},
{
type: COMPLETE_HTTP
}
];
store.dispatch(userAuthCheckActionCreator());
expect(store.getActions()).toEqual(expectedActions);
});
我喜欢这种方法的一点是,我可以清楚地看到整个 Action 序列是否按预期顺序分派(dispatch)。此外,一切都发生在模拟商店的上下文中,让 Saga 中间件分派(dispatch)操作,因此您无需操作生成器函数。
关于unit-testing - 单元测试 Redux Sagas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42145176/