单元测试。调度程序执行后,Reducer不会更改状态

时间:2019-09-06 19:13:55

标签: angular jasmine karma-runner ngrx-reducers

我正在尝试执行简单的reducer测试。新的StartLoading();调度时,应将isLoading设置为true。不幸的是,它显示: 期望的$ .isLoading = false等于true。

没有幻想。这是测试的样子:

   it('should set isLoading to true', () => {
        const isLoading = true;

        const action = new StartLoading();
        const newState = uiReducers(initialState, action);

        const expectedState = { ...initialState, isLoading };

        expect(newState).toEqual(expectedState);
    })

和减速器:

export interface UIState {
    isLoading: boolean;
}

export const initialState: UIState = {
    isLoading: false
};

export function uiReducers(state = initialState, action: UIActions) {
    switch (action.type) {
        case UIActionTypes.START_LOADING: {
            console.log('stt')
            return {
                isLoading: true,
                ...state
            };
        }
        case UIActionTypes.STOP_LOADING: {
            return {
                isLoading: false,
                ...state
            };
        }
        default:
            return {
                ...state
            }
    }

}

1 个答案:

答案 0 :(得分:1)

我认为您遇到的问题是由于object spread operator上元素的顺序造成的。

您的initialState具有isLoading = false,并且您将其设置在对象分配的右侧(通过将...state作为运算符的第二部分)。这意味着它将始终覆盖您尝试设置的isLoading。您应该尝试类似

case UIActionTypes.START_LOADING: {
            console.log('stt')
            return {
                ...state
                isLoading: true,
            };
        }

通过这种方式,您告诉操作员使用state作为原始对象,并使用新值更改isLoading属性。

如果您在文档中选中此example,则会看到状态定义在左侧,然后在右侧定义了新属性(如果它们位于多行中,则在底部)< / p>