javascript - Redux Jest 没有收到预期的值(value)

标签 javascript reactjs redux jestjs

我明白了

 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/

相关文章:

javascript - React-Redux 错误 Invalid prop `children` of type `object` supplied to `Provider`

javascript - promise 和异步操作的问题

javascript - 在 react 表的单元格中将字符串呈现为 html

javascript - javascript/reactjs中具有多个参数的递归函数

javascript - 将元素与背景大小 :cover 对齐

javascript - Jquery 侧边栏在 IE 中不起作用

javascript - 用于动态创建项目的 reducer

javascript - 如何防止 React antd 中的自动填充?

javascript - 将 CSS 类附加到元素

javascript - AJAX 获取相对于脚本的 url