2017-10-19 51 views
0

JSON数组我有以下JSON有效载荷:错误当尝试读取使用应摩卡,&Supertest

"app": { 
    "name": "myapp", 
    "version": "1.0.0", 
    "last_commit": { 
     "author_name": "Jon Snow" 
     "author_email": "[email protected]" 
    } 
} 

和以下.js文件(使用MochaSupertestShould):

var supertest = require('supertest') 
var should = require('should') 
var server = supertest.agent('http://localhost:3001') 

describe('GET /', function() { 
    it('should respond with JSON', function (done) { 
     server 
      .get('/') 
      .set('Accept', 'application/json') 
      .expect('Content-Type', /json/) 
      .expect(200) 
      .end(function (err, res) { 
       var payload = res.body.app; 
       payload.should.have.property("app"); 
       payload.should.have.property("name"); 
       payload.should.have.property("version"); 
       payload.should.have.property("last_commit"); 
       payload.should.have.property("last_commit.author_name"); 
       payload.should.have.property("last_commit.author_email"); 
       done(); 
      }); 
    }); 
}); 

当我测试应用程序时,我收到以下错误信息:

Uncaught AssertionError: expected Object { 
    "name": "myapp", 
    "version": "1.0.0", 
    "last_commit": Object { 
     "author_name": "Jon Snow" 
     "author_email": "[email protected]" 
    } 
} to have property 'last_commit.author_name' 

为什么我在这些行上收到断言错误?

payload.should.have.property("last_commit.author_name"); 
payload.should.have.property("last_commit.author_email"); 

回答

2

断言正在寻找一个叫做last_commit.author_name属性,它不存在。你可能想把它分成两个断言。

payload.should.have.property("last_commit"); 
let last_commit = payload.last_commit; 
last_commit.have.property("author_name"); 
+0

有没有更好的办法可以做到这一点?如果我有一个包含n个子元素的有效内容,该怎么办? – TheAuzzieJesus

+0

然后,您可以在断言中使用它之前提取将属性字符串转换为对象表示形式的函数。 – nilobarp

相关问题