1

在测试递增 todo id的文档中,这假定了可预测的响应。

在下面的示例中,生成了一个唯一的 id。

这怎么可能被测试?

这个测试通过了,但我不确定它是否正确,不应该根据准备回调中的内容来定义 id 吗?

切片.js

add: {
    reducer: (state, {payload}: PayloadAction<{id: string, item: Item}>) => {
        state[payload.id] = payload.item
    },
    prepare: (item: Item) => ({
        payload: {id: cuid(), item}
    })
}

slice.test.js

it('should handle add', () => {
    expect(
        reducer(
            {},
            {
                type: actions.add,
                payload: {
                    id: 'id-here?',
                    item: {
                        other: 'properties...'
                    }
                },
            }
        )
    ).toEqual({
        'id-here?': {
            other: 'properties...'
        },
    })
})
4

2 回答 2

1

您可以将prepare函数和reducer函数拉出到它自己的常量中,然后单独测试prepare:

todosSlice.js:

[...]

let nextTodoId = 0;
export const addTodoPrepare = (text) => {
    return {
        payload: {
            text,
            id: nextTodoId++
        }
    }
}
export const addTodoReducer = (state,
                               action) => {
    const {id, text} = action.payload;
    state.push({
                   id,
                   text,
                   completed: false
               });
};

const todosSlice = createSlice({
                                   name: 'todos',
                                   initialState: [],
                                   reducers: {
                                       addTodo: {
                                           prepare: addTodoPrepare,
                                           reducer: addTodoReducer,
                                       },
                                   }
                               })

[...]

todosSlice.spec.js:

import todos, {addTodo, addTodoPrepare} from './todosSlice'

describe('addTodoPrepare',
         () => {
             it('should generate incrementing IDs',
                () => {
                    const action1 = addTodoPrepare('a');
                    const action2 = addTodoPrepare('b');

                    expect(action1.payload).toEqual({
                                                        id: 0,
                                                        text: 'a'
                                                    })
                    expect(action2.payload).toEqual({
                                                        id: 1,
                                                        text: 'b'
                                                    })
                })
         })

describe('todos reducer',
         () => {
            [...]
         })
于 2020-05-06T09:24:45.037 回答
0

对于单元测试,,只需独立测试每个减速器。

对于集成测试和 e2e 测试,的。

于 2020-04-28T03:31:47.377 回答