不可变的Chai断言错误,而预期的结果等于

immutable Chai Assertion error while expected equals result

本文关键字:结果 Chai 断言 错误 不可变      更新时间:2024-06-11

我一直在使用node/redux,在使用chai进行测试时,我有以下内容:

AssertionError: expected 'Map { "winos": List [ Map { "id": 1, "x": 1, "y": 1, "movable": false }, Map { "id": 2, "x": 2, "y": 2, "movable": false }, Map { "id": 5, "x": 5, "y": 5, "movable": false } ] }'
                to equal 'Map { "winos": List [ Map { "id": 1, "x": 1, "y": 1, "movable": false }, Map { "id": 2, "x": 2, "y": 2, "movable": false }, Map { "id": 5, "x": 5, "y": 5, "movable": false } ] }'

我发现这是一个已知的错误:https://github.com/astorije/chai-immutable/issues/24.那里的人设法通过使树中的所有内容都不可变来解决这个问题,但我想我已经拥有了不可变的所有内容。

我的代码如下:

import {List, Map} from 'immutable';
import {expect} from 'chai';
export function addWino(state, wino) {
    return state.updateIn(['winos'], arr => arr.push(wino));
}
describe('setWinos', () => {
describe('addWino', () => {
    it('adds a Wino', () => {
      const wino = Map({
        id: 5,
        x:5,
        y:5,
        movable: false
      });
      const nextState = addWino(state, wino);
      expect(nextState).to.equal(Map({
        winos: List.of([
          Map({
            id: 1,
            x:1,
            y:1,
            movable: false
          })
        ],
        [
          Map({
            id: 2,
            x:2,
            y:2,
            movable: false
          })
        ],
        [
          Map({
            id: 5,
            x:5,
            y:5,
            movable: false
          })
        ])
      }));
    });
  });
}

我也已经尝试过.eql().to.deep.equal()。谢谢你的帮助。

我找到了原因,而不是:

winos: List.of([
      Map({
        id: 1,
        x:1,
        y:1,
        movable: false
      })
    ],
    [
      Map({
        id: 5,
        x:5,
        y:5,
        movable: false
      })
    ])
  }));

我应该有:

winos: List.of(
      Map({
        id: 1,
        x:1,
        y:1,
        movable: false
      }),
      Map({
        id: 5,
        x:5,
        y:5,
        movable: false
      })
    )
  }));

不需要的[],并创建一个附加列表。

我认为您的断言类型错误。assert.equal(和类似的)通常测试两件事是否"相同"。对于对象,如果它不是完全相同的对象,则这不成立。即使内容相同。为您的断言框架寻找类似"deepEqual"的东西

请参见此处:https://tonicdev.com/lipp/deep-equal

var assert = require('assert')
var x = {a: 123}
var y = x
assert.equal(x, y)
var u = {a: 123}
assert.deepEqual(x, u, 'this is ok')
assert.equal(x, u, 'this fails')