0

我正在尝试执行简单的减速器测试。新的开始加载();调度这应该将 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
            }
    }

}
4

1 回答 1

1

我相信您面临的问题是由于object spread operator.

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

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

这样,您就告诉操作员将用作原始对象并使用新值state更改属性。isLoading

如果您在文档中查看此示例,您将看到左侧定义了状态,然后在右侧定义了新属性(如果它们位于多行中,则在底部)

于 2019-09-06T20:14:13.923 回答