Chai/Mocha 不可变测试一直失败

Chai/Mocha immutable tests consistently failing

我正在学习教程 here,发现除了第一个最基本的 chai 测试之外,几乎所有的测试都对我失败了。这是失败测试的当前示例

import {List, Map} from 'immutable';
import {expect} from 'chai';

import {setEntries} from '../src/core';

describe('application logic', () => {
    describe('setEntries', () => {
        it('adds the entries to the state', () => {
            const state = Map();
            const entries = List.of('Trainspotting', '28 Days Later');
            const nextState = setEntries(state, entries);
            expect(nextState).to.equal(Map({
                entries: List.of('Trainspotting', '28 Days Later')
            }));
        });
    });
});

这里是测试代码:

import {List} from 'immutable';

export function setEntries(state, entries){
    return state.set('entries', entries);
}

这是失败的错误消息:

1) application logic setEntries adds the entries to the state:

      AssertionError: expected { Object (size, _root, ...) } to equal { Object (size, _root, ...) }
      + expected - actual

                 "size": 2
               }
             ]
           ]
      -    "ownerID": [undefined]
      +    "ownerID": {}
         }
         "size": 1
       }

我似乎找不到关于此错误含义的任何有意义的文档,也没有看到本教程的任何其他用户提及类似问题。知道这是窒息的地方吗?

您不能对不可变对象使用常规相等性检查。相反,使用类似 Immutable.is():

import Immutable, {List, Map} from 'immutable';

...

expect(
  Immutable.is(nextState, Map({
    entries: List.of('Trainspotting', '28 Days Later')
  }))
).to.be.true;

或者更好,使用 chai-immutable:

import chai, {expect} from 'chai';
import chaiImmutable  from 'chai-immutable';

chai.use(chaiImmutable);

使用后者,您的测试用例可以保持不变。

您必须在文件开头添加以下代码。

 import chai from 'chai';
 import chaiImmutable from 'chai-immutable';

 chai.use(chaiImmutable);