我希望这个简单的例子能说明它们之间的区别
断言
var assert = require('chai').assert
const foo = 'bar'
const beverages = { tea: [ 'chai', 'matcha', 'oolong' ] };
assert.typeOf(foo, 'string'); // without optional message
assert.typeOf(foo, 'string', 'foo is a string'); // with optional message
assert.equal(foo, 'bar', 'foo equal `bar`');
assert.lengthOf(foo, 3, 'foo`s value has a length of 3');
assert.lengthOf(beverages.tea, 3, 'beverages has 3 types of tea');
在所有情况下,断言样式都允许您在断言语句中包含可选消息作为最后一个参数。如果您的断言未通过,这些将包含在错误消息中。
注意
expect 和 should 使用可链接的语言来构造断言,但它们在断言最初构造的方式上有所不同。在 should 的情况下,还有一些注意事项和额外的工具可以克服这些注意事项。
期待
var expect = require('chai').expect
const foo = 'bar'
const beverages = { tea: [ 'chai', 'matcha', 'oolong' ] };
expect(foo).to.be.a('string');
expect(foo).to.equal('bar');
expect(foo).to.have.lengthOf(3);
expect(beverages).to.have.property('tea').with.lengthOf(3);
Expect 允许您在任何可能发生的失败断言之前包含任意消息。
var answer = 43;
// AssertionError: expected 43 to equal 42.
expect(answer).to.equal(42);
// AssertionError: topic [answer]: expected 43 to equal 42.
expect(answer, 'topic [answer]').to.equal(42);
这在与非描述性主题(例如布尔值或数字)一起使用时会派上用场。
应该
should 样式允许与期望接口相同的可链接断言,但是它使用 should 属性扩展每个对象以启动链。此样式在与 Internet Explorer 一起使用时存在一些问题,因此请注意浏览器兼容性。
var should = require('chai').should() //actually call the function
const foo = 'bar'
const beverages = { tea: [ 'chai', 'matcha', 'oolong' ] };
foo.should.be.a('string');
foo.should.equal('bar');
foo.should.have.lengthOf(3);
beverages.should.have.property('tea').with.lengthOf(3);
期望和应该的区别
首先,请注意,expect require 只是对 expect 函数的引用,而 should require 函数正在执行。
var chai = require('chai')
const expect = chai.expect
const should = chai.should();
expect 接口提供了一个函数作为链接语言断言的起点。它适用于 node.js 和所有浏览器。
should 接口扩展了 Object.prototype 以提供单个 getter 作为语言断言的起点。它适用于 node.js 和除 Internet Explorer 之外的所有现代浏览器。