我写了一个使用yield select
来获得Redux存储状态一部分并将其存储在局部变量中的传奇。变量是一个具有三个不同键的对象,每个键的值是其中的对象数组。
我的redux-saga测试一直失败,因为我在saga中创建了此局部变量,该局部变量使用来自初始yield select
的数据,并且在测试中该变量始终为undefined
,这导致了我的其余部分在那个传奇中测试失败。我已经看到了很多关于如何在redux传奇中模拟yield select
的返回状态的示例,但这总是在下一个redux-saga调用的上下文中。如何模拟局部变量的返回状态?
这是我的代码:
export default function* orderSelectionFlow({ payload }) {
try {
const orders = yield select(getOrders); // retrieve relevant part of redux store
const activeOrder = orders[payload.orderStatus].find(order => order.id === payload.orderId); // this variable is always undefined in my tests, because I am not sure how to mock `orders` for a local variable.
const activeOrderId = payload.orderId;
const isConnected = yield select(getIsConnected); // test for this select fails because activeOrder is undefined
我的测试(直到相关时间)
describe('test order selection flow', () => {
const navSpy = jest.spyOn(AppNavigator, 'navigate');
const action = {
type: 'galactica/orders/VIEW',
payload: {
orderStatus: 'OPEN',
orderId: 1
}
};
afterAll(() => {
jest.resetModules();
navSpy.mockRestore();
});
it.next = sagaHelper(orderSelectionFlow(action));
it.next('should get all orders', (result) => {
expect(result).toEqual(select(getOrders));
});
it.next('should use connected state', (result) => {
expect(result).toEqual(select(getIsConnected));
});
订单目前未定义,但如果我可以模拟该值,则为
orders: {
'OPEN': {
orderId: 1
}
}
答案 0 :(得分:0)
我会尝试使用redux-saga-tester
:https://github.com/wix/redux-saga-tester。让您在选项中指定初始状态。我不太确定您的所有代码是什么样的,但是我认为您可以执行以下操作。
describe('test order selection flow', () => {
const navSpy = jest.spyOn(AppNavigator, 'navigate');
const action = {
type: 'galactica/orders/VIEW',
payload: [{
orderStatus: 'OPEN',
orderId: 1
}]
};
afterAll(() => {
jest.resetModules();
navSpy.mockRestore();
});
it('should get all orders', (result) => {
const tester = new SagaTester({
initialState: {
orders: {
'OPEN': {
orderId: 1
}
}
}
});
tester.start(saga);
tester.dispatch(action);
// ... do your expects here
// You may need to use `tester.waitFor` to wait for an action to be dispatched
// If you want to expect a certain action was called, use `getCalledActions`
});