Chai: 如何使用‘ should’语法测试未定义

基于 这个教程测试 angularjs 应用程序 chai,我想添加一个测试未定义的值使用“应该”样式。这种做法失败了:

it ('cannot play outside the board', function() {
scope.play(10).should.be.undefined;
});

带有错误“ TypeError: 无法读取未定义的属性‘ should’”,但测试通过了“ Expect”样式:

it ('cannot play outside the board', function() {
chai.expect(scope.play(10)).to.be.undefined;
});

我怎样才能让它与“应该”一起工作?

64027 次浏览

Try this:

it ('cannot play outside the board', function() {
expect(scope.play(10)).to.be.undefined; // undefined
expect(scope.play(10)).to.not.be.undefined; // or not
});

This is one of the disadvantages of the should syntax. It works by adding the should property to all objects, but if a return value or variable value is undefined, there isn't a object to hold the property.

The documentation gives some workarounds, for example:

var should = require('chai').should();
db.get(1234, function (err, doc) {
should.not.exist(err);
should.exist(doc);
doc.should.be.an('object');
});

You can wrap your function result in should() and test for a type of "undefined":

it ('cannot play outside the board', function() {
should(scope.play(10)).be.type('undefined');
});
should.equal(testedValue, undefined);

as mentioned in chai documentation

(typeof scope.play(10)).should.equal('undefined');

The answer by @david-norman is correct as per the documentation, I had a few issues with setup and instead opted for the following.

(typeof scope.play(10)).should.be.undefined;

Test for undefined

var should = require('should');
...
should(scope.play(10)).be.undefined;

Test for null

var should = require('should');
...
should(scope.play(10)).be.null;

Test for falsy, i.e. treated as false in conditions

var should = require('should');
...
should(scope.play(10)).not.be.ok;

I struggled to write the should statement for undefined tests. The following doesn't work.

target.should.be.undefined();

I found the following solutions.

(target === undefined).should.be.true()

if can also write it as a type check

(typeof target).should.be.equal('undefined');

Not sure if the above is the right way, but it does work.

According to Post from ghost in github

Don't forget about a combination of have and not keywords:

const chai = require('chai');
chai.should();
// ...
userData.should.not.have.property('passwordHash');