我明白了
Expected value to equal: [{"id": 1, "text": "Run the tests"}, {"id": 0, "text": "Use Redux"}] Received: [{"id": 0, "text": "Use Redux"}, {"id": 1, "text": "Run the tests"}]
我不太明白如何让这个 reducer 测试通过。我引用了各种 github 项目来更好地理解测试。我不确定我能做些什么来使测试通过。这是我所拥有的。
我正在使用 jest 进行测试。
actions/actions.js
let nextTodoId = 0;
export const addPost = text => ({
type: 'ADD_POST',
id: nextTodoId++,
text
})
reducer /myPosts
const initialState = [
{
text: 'Use Redux',
id: 0
}
]
const myPosts = (state = initialState, action) => {
switch(action.type){
case 'ADD_POST':
const post = {
id:state.reduce((maxId, post) => Math.max(post.id, maxId), -1) + 1,
text:action.text,
}
return [...state, post];
default:
return state
}
}
export default myPosts
测试/reducers.js
import { addPost } from '../actions/actions';
import myPosts from '../reducers/myPosts';
import uuid from 'uuid';
describe('myPosts myPosts', () => {
it('should return the initial state', () => {
expect(myPosts(undefined, {})).toEqual([
{
text: 'Use Redux',
id: 0
}
])
})
it('should handle ADD_POST', () => {
expect(
myPosts([], {
type: 'ADD_POST',
text: 'Run the tests'
})
).toEqual([
{
text: 'Run the tests',
id: 0
}
])
expect(
myPosts(
[
{
text: 'Use Redux',
id: 0
}
],
{
type: 'ADD_POST',
text: 'Run the tests',
id:0
}
)
).toEqual([
{
text: 'Run the tests',
id: 1
},
{
text: 'Use Redux',
id: 0
}
])
})
})
最佳答案
问题是您在添加新帖子之前扩展了先前的状态...
将您的 reducer 更改为:
return [post, ...state];
您编写的方式...新帖子放置在状态数组的末尾。如果您希望新帖子首先显示,这将解决该问题。
关于javascript - Redux Jest 没有收到预期的值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53452505/