【问题标题】:How do I write a mocha test with a result array?如何使用结果数组编写 mocha 测试?
【发布时间】:2016-06-28 15:49:28
【问题描述】:

我正在尝试动态编写 mocha 测试,而不是为 res.body.result 中的每个项目编写期望。我有这样的 json 响应:

{
  "ok": true,
  "result": {
    "year": "2000",
    "makes": [
      "Acura",
      "Audi",
      "BMW"
    ]
  }
}

而不是为每个品牌写这个:

describe('Decode VIN', function (){
    it('should return 200 response', function (done){
        api.get('/makes_year?year=2000')
            .set('Accept', 'application.json')
            .expect(200)
            .end(function(err, res) {
                expect(res.body.ok).to.equal(true)
                expect(res.body.result.year).to.equal("2000")
                expect(res.body.result.makes).to.equal("Acura")
                expect(res.body.result.makes).to.equal("Audi")
                done();
            })
    });
});

我怎样才能迭代地做到这一点?

编辑:我尝试在 describe 语句内外声明 expectedMakes。为简洁起见,这只是两者之一。

var expectedMakes = [
    "Acura",
    "Audi",
    "BMW"
];

describe('Makes By Year', function (){
    it('should return 200 response, body.ok, and an array of vehicle makes', function (done){
        api.get('/makes_year?year=2000')
            .set('Accept', 'application.json')
            .expect(200)
            .end(function(err, res) {
                expect(res.body.ok).to.equal(true)
                expect(res.body.result.year).to.equal("2000")
                expect(res.body.result.makes).to.equal(expectedMakes)
                done();
            })
    });
});

我得到这个结果:

  Uncaught AssertionError: expected [ Array(37) ] to equal [ Array(37) ]
  + expected - actual

【问题讨论】:

    标签: javascript unit-testing mocha.js supertest


    【解决方案1】:

    预期值位于您的测试中。一种方法是在测试中按预期存储所有 makes 并断言

    var expectedMakes = [
       'Acura',
       'Audi',
       ... 
    ]
    expect(res.body.result.makes).toEqual(expectedMakes)
    

    这将断言列表严格相等,每个项目都在与expectedMakes匹配的位置

    【讨论】:

    • 我尝试在 describe 内部和外部声明 make 数组。它失败了,我还有其他方法吗?
    猜你喜欢
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2023-03-31
    • 2015-03-07
    • 1970-01-01
    相关资源
    最近更新 更多