2017-10-19 82 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

相關問題