使用 mocha/chai 进行基本的 React/redux 测试

IT技术 reactjs mocha.js redux chai
2021-05-20 17:38:33

我是 react/redux 世界的新手,我使用此代码创建了 redux todo 应用程序,现在我想为它编写测试,我创建了以下规范:

import {expect} from 'chai'
import todoApp from '../src/reducers'
import {setVisibilityFilter} from '../src/actions'

describe('reducer', ()=> {
    it('Set correctly visibility filter', ()=>{
        const setVisibilityFilterAction = setVisibilityFilter('SHOW_ALL')
        const initialState={};
        const nextState= todoApp(initialState, setVisibilityFilterAction)
        const expectedState ={
                todos:[],
                visibilityFilter:'SHOW_ALL' 
            }
        expect(nextState).to.equal(expectedState);
    })
})  

但是断言失败了,错误是:

AssertionError: expected { Object (todos, visibilityFilter) } to equal { Object (todos, visibilityFilter) }
      + expected - actual

试图打印对象并且它们(expectedStatenextState)都具有相同的数据:

{
   todos:[],
   visibilityFilter: "SHOW_ALL"
}

为什么失败了?

1个回答

equal()来自 Chai 的expect界面是一个严格的平等检查。听起来您想要eql().deep.equal()

// Equivalent to nextState === expectedState
expect(nextState).to.equal(expectedState);

// Instead:
expect(nextState).to.eql(expectedState);

// Or:
expect(nextState).to.deep.equal(expectedState);