Chai:如何使用'should'语法测试undefined

the*_*ict 92 javascript testing angularjs chai

教程中使用chai测试angularjs应用程序时,我想使用"should"样式为未定义的值添加测试.这失败了:

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

错误"TypeError:无法读取属性'应该'未定义",但测试通过了"expect"样式:

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

如何让它与"应该"一起工作?

Dav*_*man 76

这是should语法的缺点之一.它的工作原理是将should属性添加到所有对象,但如果返回值或变量值未定义,则没有对象来保存该属性.

文档提供了一些解决方法,例如:

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

  • `should.not.exist`将验证该值是否为"null",因此该答案不正确.@daniel的答案如下:`should.equal(testedValue,undefined);`.那应该是公认的答案. (13认同)
  • 我每月都会回答这个问题(不是文档):-) (7认同)

dan*_*iel 47

should.equal(testedValue, undefined);
Run Code Online (Sandbox Code Playgroud)

正如柴文献中所述

  • omg,有什么可以解释的?你期望testsValue === undefined,所以你测试它.许多开发人员首先首先将testsValue放入,然后使用should链接它,最终会出现错误... (12认同)
  • 这不是开箱即用的,并且在[.equal()`]的API文档中找不到它(http://chaijs.com/api/bdd/#method_equal).我能理解@OurManInBananas为什么要求解释.这是一个意外的使用,作为接受两个参数的函数,而不是预期的链式方法形式接受预期值的单个参数.你只能通过导入/要求和分配一个被调用的`.should()`来实现这个目的,如@DavidNorman和[文档](http://chaijs.com/guide/styles/#)所接受的答案中所述.应该-演员). (5认同)

Pet*_*hev 17

测试未定义

var should = require('should');
...
should(scope.play(10)).be.undefined;
Run Code Online (Sandbox Code Playgroud)

测试null

var should = require('should');
...
should(scope.play(10)).be.null;
Run Code Online (Sandbox Code Playgroud)

测试假,即在条件下视为假

var should = require('should');
...
should(scope.play(10)).not.be.ok;
Run Code Online (Sandbox Code Playgroud)

  • 没有用?这是bdd样式IMO中未定义测试的最佳答案,但它需要安装其他npm软件包(应该包),我认为不值得为此安装其他软件包,虽然很棒的答案 (2认同)

小智 16

(typeof scope.play(10)).should.equal('undefined');
Run Code Online (Sandbox Code Playgroud)


Vir*_*ths 7

我努力为未定义的测试编写should语句.以下不起作用.

target.should.be.undefined();
Run Code Online (Sandbox Code Playgroud)

我找到了以下解决方案.

(target === undefined).should.be.true()
Run Code Online (Sandbox Code Playgroud)

如果还可以将其写为类型检查

(typeof target).should.be.equal('undefined');
Run Code Online (Sandbox Code Playgroud)

不确定上述是否正确,但确实有效.

根据Github中鬼的帖子


Epo*_*okK 5

试试这个:

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
});
Run Code Online (Sandbox Code Playgroud)