[英]Mocha and Chai unit testing AssertionError
我不明白为什么这些都失败了我尝试过的变化是:
response.body.should.be.a('object').and.to.have.property('id');
和
response.body.should.have.property('id');
我收到错误 Uncaught AssertionError: expected { Object (starss) } to have property 'id'
这是来自 Postman 的我的 JSON 有效载荷
{
"starss": {
"id": 1,
"name": "1",
"discovery_name": "1",
"imageFileName": "test1.jpg",
"datediscovered": "2001-01-01T00:00:00.000Z",
"colour": "1",
"mass": "1.000",
"dfe": "1.000",
"galaxy_origin": "1",
"star_categories_id": 1,
"createdAt": "2021-12-03",
"updatedAt": "2021-12-12"
}
}
这是我的摩卡测试
describe('GET/stars/:id',() => {
it("it should get one star by ID", (done) =>
{
// Uncaught AssertionError: expected { Object (starss) } to be a starss
// star GET by ID
const starId = 1;
chai.request(server)
.get("/stars/" + starId )
.end((err,response)=>{
response.should.have.status(200);
response.body.should.be.a('object');
response.body.should.be.a('object').and.to.have.property('id');
response.body.should.have.property('id');
// response.body.should.have.property('name');
// response.body.should.have.property('discovery_name');
// response.body.should.have.property('imageFileName');
// response.body.should.have.property('datediscovered');
// response.body.should.have.property('colour');
// response.body.should.have.property('mass');
// response.body.should.have.property('dfe');
// response.body.should.have.property('galaxy_origin');
// response.body.should.have.property('star_categories_id');
done();
});
});
它没有找到 id 属性的原因是因为响应正文只有 starss 的键。 您需要将 go 放入星辰 object 才能访问其密钥。 我曾经使用 mocha/chai codepen 来验证结果:
mocha.setup('bdd'); var expect = chai.expect; describe('GET/stars/:id',function() { var body = { "starss": { "id": 1, "name": "1", "discovery_name": "1", "imageFileName": "test1.jpg", "datediscovered": "2001-01-01T00:00:00.000Z", "colour": "1", "mass": "1.000", "dfe": "1.000", "galaxy_origin": "1", "star_categories_id": 1, "createdAt": "2021-12-03", "updatedAt": "2021-12-12" } } it("body to be object", function() { expect(body).to.be.a('object'); }) it("it should get one star by ID", function() { console.log(body) expect(body.starss).to.contain.key('id'); // response.body.should.have.property('"id"'); }) }); mocha.run();
codepen 的 URL 在这里: https://codepen.io/alexpyzhianov/pen/KVbeyO
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.