我正在尝试测试一个数组,例如:
let projects = [
{
"id": "55a75be01fa2c7ff76a2ce7a",
"title: "Only-Ben",
"other_keys": "that can contain objects or arrays"
},
{
"id": "55a75be01fa2c7ff76a2ce7d",
"title: "Only-Thomas"
},
{
"id": "55a75be01fa2c7ff76a2ce7c",
"title: "Other-Project"
}
];
目标是测试数组
- 包含一个有键的元素
{title: 'Only Ben'}
- 不包含有键的元素
{title: 'Only Thomas'}
我目前正在使用chai.js and 柴的事情通过这个测试:
projects.should.include.something.that.deep.have.property('title', 'Only Thomas');
这是我的错误响应:
Uncaught TypeError: Cannot read property 'something' of undefined
为了让事情更清楚,我尝试运行 Chai Things 文档中给出的示例:
[{ a: 'cat' }, { a: 'dog' }].should.include.something.that.deep.equals({ a: 'cat' })
我仍然收到类似的错误响应:
Uncaught TypeError: Cannot read property 'something' of undefined
在我看来,这个问题可能是由使用引起的Babel。我的 Node 项目大量使用 ES6 语法,这就是我使用 Babel 的原因。为了使用 babel 运行摩卡测试,我使用了 babel-hook:
(in package.json)
{
"scripts": {
"test": "./node_modules/.bin/mocha --require babelhook --reporter spec",
}
}
断言数组时如何修复此未定义错误?
==EDIT==
我做了 2 个测试(有和没有 babel)来确认 Babel 是这个场景中的问题。他们来了:
1. 不使用babel进行测试
var chai = require("chai");
chai.should();
chai.use(require('chai-things'));
describe('Array', function() {
it('Test array', function(cb){
[{ a: 'cat' }, { a: 'dog' }].should.include.something.that.deep.equals({ a: 'cat' })
cb();
});
});
Result: 测试通过
2.用babel测试
import chai from 'chai';
let should = chai.should;
let expect = chai.expect;
import chai_things from 'chai-things';
chai.use(chai_things);
describe('Array', function() {
it('Test array', function(cb){
[{ a: 'cat' }, { a: 'dog' }].should.include.something.that.deep.equals({ a: 'cat' })
cb();
});
});
Result: Error: TypeError: Cannot read property 'something' of undefined