首页 > 解决方案 > 理解 Chai 的断言(期望式)

问题描述

这里有什么区别?

it("should be 5", () => {
  expect(num).equal(5);
});

it("should be 5", () => {
  expect(num).to.be.equal(5);
});

如果我使用第一种方式或第二种方式,它没有任何区别。至少在我看来是这样。

“.to.be.”的目的是什么?

仅仅是为了拥有更类似于实际句子的东西吗?或者它有什么功能?

标签: javascriptunit-testingautomated-testsmocha.jschai

解决方案


文档

以下内容作为可链接的 getter 提供,以提高断言的可读性。

看这个测试用例:

import { expect } from 'chai';

const num = 5;

describe('62770625', () => {
  it('should be 5', () => {
    expect(num).equal(5);
  });

  it('should be 5', () => {
    expect(num).to.be.equal(5);
  });

  it('should have members', () => {
    expect([{ a: 1 }]).deep.members([{ a: 1 }]); 
    expect([{ a: 1 }]).to.have.deep.members([{ a: 1 }]);
  });
});

它们都可以工作,但是通过这些语言链,我们可以得到:

  • 更好的可读性
  • 人性化
  • 良好的语义

推荐阅读