【问题标题】:Error when trying to read JSON array using Should, Mocha, & Supertest尝试使用 Should、Mocha 和 Supertest 读取 JSON 数组时出错
【发布时间】:2017-10-19 03:04:03
【问题描述】:

我有以下JSON 有效载荷:

"app": {
    "name": "myapp",
    "version": "1.0.0",
    "last_commit": {
        "author_name": "Jon Snow"
        "author_email": "my@email.com"
    }
}

以及以下.js 文件(使用Mocha、Supertest 和Should):

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": "my@email.com"
    }
} to have property 'last_commit.author_name'

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

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

【问题讨论】:

    标签: json node.js mocha.js supertest should.js


    【解决方案1】:

    Assertion 正在寻找一个名为 last_commit.author_name 的属性,该属性不存在。你可能想把它分成两个断言。

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

    【讨论】:

    • 有没有更好的方法可以做到这一点?如果我有一个包含 n 个子元素的子元素的有效负载怎么办?
    • 然后你可以提取一个函数,将属性字符串转换为对象表示,然后在断言中使用它。
    猜你喜欢
    • 2016-06-05
    • 2015-11-23
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多