我有这个减速器:
import { fromJS } from 'immutable';
import { DEFAULT_ACTION, SOURCES_LOADED, SOURCES_REQUEST } from './constants';
export const initialState = fromJS({
sources: null,
loading: false
});
function appReducer(state = initialState, action) {
switch (action.type) {
case SOURCES_REQUEST:
return state
.set('loading', true);
case SOURCES_LOADED:
return state
.set('sources', action.payload.sources)
.set('loading', false);
case DEFAULT_ACTION:
return state;
default:
return state;
}
}
export default appReducer;
此测试:
import { fromJS } from 'immutable';
import reducer from '../reducer';
import * as types from '../constants';
describe('application reducers', () => {
it('should return the initial state', () => {
expect(reducer(undefined, {})).toEqual(fromJS(
{
sources: null,
loading: false
}
));
});
it('should handle the sources request', () => {
expect(reducer({ loading: true }, {
type: types.SOURCES_REQUEST
})).toEqual(fromJS({ loading: true }));
});
});
第二项测试失败:
TypeError: state.set is not a function
11 | case SOURCES_REQUEST:
12 | return state
> 13 | .set('loading', true);
| ^
14 | case SOURCES_LOADED:
15 | return state
16 | .set('sources', action.payload.sources)
如何将测试添加到这些减速器中,因为这是redux sagas,由于我发现的文档更接近我的需求,因此我正在遵循https://redux.js.org/recipes/writing-tests。
答案 0 :(得分:1)
您的减速器期望收到的state
是immutable
对象。
但是在第二个测试中,您将其传递给一个普通的javascript对象,该对象没有尝试调用的.set
方法。
it('should handle the sources request', () => {
expect(reducer(fromJS({
loading: true
}), {
type: types.SOURCES_REQUEST
})).toEqual(fromJS({
loading: true
}));
});
,或者在这种情况下,您可以将其传递给undefined
,而减速器将使用initialState