【问题标题】:chai: expect object to have array of objects like (in format)chai:期望对象具有对象数组,例如(格式)
【发布时间】:2020-07-13 00:25:36
【问题描述】:

我正在尝试使用 TDD 为 node.js 应用程序编写测试,但我不知道如何为我的 Products Route get() 函数编写 chai expect 测试。

// productsController.js

let items = [
   {
        id: 1,
        name: 'Product 1',
        description: 'Product1 description',
       price: 19.00
   }
];

module.exports = {
    get(_, res) {
        res.json({items});
    }
};

我已经阅读了几次文档,但我似乎不太明白如何测试响应对象是否应包含键 items,其中值是 array 的 @987654325 @ 与上面提到的架构类似。

我尝试过的:

// products.test.js

const { get, getById } = require('../../routes/productsController');

const res = {
    jsonCalledWith: {},
    json(arg) {
        this.jsonCalledWith = arg
    }
}

describe('Products Route', function() {
    describe('get() function', function() {
        it('should return an array of products ', function() {
            get(req, res);
            expect(res.jsonCalledWith).to.be.have.key('items').that.contains.something.like({
                id: 1,
                name: 'name',
                description: 'description',
                price: 18.99     
            });
        });
    });
});

但是,我收到此错误: AssertionError: expected { Object (items) } to be an array

有人知道我怎样才能成功编写这个测试吗?

【问题讨论】:

    标签: javascript node.js mocha.js tdd chai


    【解决方案1】:

    我想通了!

    // products.test.js
    
    const chai = require('chai');
    chai.use(require('chai-json-schema'));
    const expect = chai.expect;
    
    const { get } = require('../../routes/productsController');
    
    let req = {
        body: {},
        params: {},
    };
    
    const res = {
        jsonCalledWith: {},
        json(arg) {
            this.jsonCalledWith = arg
        }
    }
    
    let productSchema = {
        title: 'productSchema',
        type: 'object',
        required: ['id', 'name', 'description', 'price'],
        properties: {
          id: {
            type: 'number',
          },
          name: {
            type: 'string'
          },
          description: {
            type: 'string',
          },
          price: {
            type: 'number',
          },
        }
      };
    
    describe('Products Route', function() {
        describe('get() function', function() {
            it('should return an array of products ', function() {
                get(req, res);
                expect(res.jsonCalledWith).to.be.have.key('items');
                expect(res.jsonCalledWith.items).to.be.an('array');
                res.jsonCalledWith.items.forEach(product => expect(product).to.be.jsonSchema(productSchema));
            });
        });
    });
    

    原来插件chai-json-schema 允许验证 json 对象以满足预定义的模式。

    【讨论】:

      【解决方案2】:

      我认为您收到错误是因为预期的输出是一个数组,以完成您需要的测试:

      it('Check route list all users', (done) => {
              api.get('/usuarios')
                  .set('Accept', 'application/json; charset=utf-8')
                  .expect(200)
                  .end((err, res) => {
                      expect(res.body).to.be.an('array');
                      expect(res.body.length).to.equal(1);
                      done();
                  });
      });
      

      这是一个将数组作为 json 响应返回的示例。

      这里是对来自路由的对象 User 实例的相同测试:

      it('Check get by id return 200', (done) => {
                  api.get('/usuarios/1')
                  .set('Accept', 'application/json; charset=utf-8')
                  .expect(200)
                  .end((err, res) =>{
                      expect(res.body).to.have.property('nome');
                      expect(res.body.nome).to.equal('abc');
                      expect(res.body).to.have.property('email');
                      expect(res.body.email).to.equal('a@a.com');
                      expect(res.body).to.have.property('criacao');
                      expect(res.body.criacao).to.not.equal(null);
                      expect(res.body).to.have.property('atualizado');
                      expect(res.body.atualizado).to.not.equal(null);
                      expect(res.body).to.have.property('datanascimento');
                      expect(res.body.datanascimento).to.not.equal(null);
                      expect(res.body).to.have.property('username');
                      expect(res.body.username).to.equal('abcdef');
                      expect(res.body).to.have.property('statusmsg');
                      expect(res.body.statusmsg).to.equal('status');
                      expect(res.body).to.have.property('genero');
                      expect(res.body.genero).to.equal('M');
                      expect(res.body).to.have.property('descricao');
                      expect(res.body.descricao).to.equal('descricao');
                      done();
                  });
          });
      

      我的例子我使用mochachaisupertest

      希望对您有所帮助,如果您需要更多说明,请告诉我。

      【讨论】:

      • 感谢发帖!查看我的答案,我相信这是对“用户”实例验证的改进
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 2023-04-02
      • 2020-04-28
      • 1970-01-01
      • 2020-08-03
      • 2020-10-19
      相关资源
      最近更新 更多