zer*_*ing 31 node.js should.js
我尝试在节点中使用测试工具mocha.请考虑以下测试方案
var requirejs = require('requirejs');
requirejs.config({
//Pass the top-level main.js/index.js require
//function to requirejs so that node modules
//are loaded relative to the top-level JS file.
nodeRequire: require
});
describe('Testing controller', function () {
it('Should be pass', function (done) {
(4).should.equal(4);
done();
});
it('Should avoid name king', function (done) {
requirejs(['../server/libs/validate_name'], function (validateName) {
var err_test, accountExists_test, notAllow_test, available_test;
validateName('anu', function (err, accountExists, notAllow, available) {
accountExists.should.not.be.true;
done();
});
});
});
});
Run Code Online (Sandbox Code Playgroud)
作为测试结果我有:
$ make test
./node_modules/.bin/mocha \
--reporter list
. Testing controller Should be pass: 0ms
1) Testing controller Should avoid name anu
1 passing (560 ms)
1 failing
1) Testing controller Should avoid name anu:
Uncaught TypeError: Cannot read property 'should' of null
at d:\townspeech\test\test.spec.js:23:30
at d:\townspeech\server\libs\validate_name.js:31:20
at d:\townspeech\test\test.spec.js:22:13
at Object.context.execCb (d:\townspeech\node_modules\requirejs\bin\r.js:1869:33)
at Object.Module.check (d:\townspeech\node_modules\requirejs\bin\r.js:1105:51)
at Object.Module.enable (d:\townspeech\node_modules\requirejs\bin\r.js:1376:22)
at Object.Module.init (d:\townspeech\node_modules\requirejs\bin\r.js:1013:26)
at null._onTimeout (d:\townspeech\node_modules\requirejs\bin\r.js:1646:36)
at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
make: *** [test] Error 1
Run Code Online (Sandbox Code Playgroud)
第一次传递没有任何复杂,但第二次,似乎,无法附加模块shouldjs.为什么?
小智 29
你可以直接使用
should.not.exist(err);
Run Code Online (Sandbox Code Playgroud)
这是should库的一个已知问题:当它扩展时object,它当然只有在你有一个具体对象时才有效.因为null,根据定义,意味着您没有对象,您不能在其上调用任何方法或访问其任何属性.
因此,should在这种情况下不可用.
基本上,您有两种方法可以解决这个问题:
actual和expected.这样,只要你没有想到null,你在开头有一个对象,因此可以访问它的should属性.但是,这并不好,因为它改变了语义,并不适用于所有情况.should通过另一个没有此问题的断言库来交换库.就个人而言,我选择2,我个人最喜欢的是节点断言(这是我写的,因此它是我最喜欢的).
无论如何,还有很多其他选择,比如期待.随意使用最适合您编写测试风格的任何这些断言库.
我在这里没有提到的另一个选项:
should(err === null).be.null
Run Code Online (Sandbox Code Playgroud)
在你的例子中,那将是:
should(accountExists).be.null
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23606 次 |
| 最近记录: |