chai: ожидайте, что объект будет иметь массив таких объектов, как (в формате) - PullRequest
0 голосов
/ 13 июля 2020

Я пытаюсь написать тест для приложения node.js, используя TDD, но не могу понять, как написать тест chai expect для моей функции Products Route get().

// productsController.js

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

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

Я читал документы несколько раз, но, похоже, не совсем понимаю, как я могу проверить, должен ли объект ответа содержать ключ items, где значение равно array из 'products' со схемой, подобной указанной выше.

Что я пробовал:

// 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

Кто-нибудь знает, как могу ли я успешно написать этот тест?

Ответы [ 2 ]

0 голосов
/ 13 июля 2020

Я понял!

// 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 объекты на соответствие предопределенной схеме.

0 голосов
/ 13 июля 2020

Я думаю, вы получаете сообщение об ошибке, потому что ожидаемый результат представляет собой массив, чтобы выполнить sh ваши тесты, которые вам нужны:

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();
            });
    });

В моем примере я использую mocha и chai и supertest.

Надеюсь, это поможет, если вам нужны дополнительные разъяснения, дайте мне знать.

...