笑话中的toEqual()对于不可变对象如何解释?

时间:2019-03-25 06:19:35

标签: jestjs immutable.js

我希望这两个toEqual()测试都能通过。第一个通过,但第二个没有通过。为什么?

test('something', () => {
  const m = Map({
    a: 1,
    b: 2,
  })

  expect(m.valueSeq()).toEqual(m.valueSeq());
  expect(m.valueSeq().filter(_ => true)).toEqual(m.valueSeq());
});

1 个答案:

答案 0 :(得分:0)

此行:

expect(m.valueSeq().filter(_ => true)).toEqual(m.valueSeq());

...调用toEqual which calls equal作为自定义匹配项传递给iterableEquality

const pass = equals(received, expected, [iterableEquality]);

iterableEquality最终在this line上返回false

if (a.constructor !== b.constructor) {
  return false;
}

...因为构造函数不相等:

const { Map } = require('immutable');

test('something', () => {
  const m = Map({
    a: 1,
    b: 2,
  })

  const seq = m.valueSeq();
  const filter = m.valueSeq().filter(_ => true);

  console.log(seq.constructor);  // [Function: ToIndexedSequence]
  console.log(filter.constructor);  // [Function: IndexedCollection]

  expect(seq.constructor).not.toBe(filter.constructor); // Success! (different constructors)
});