Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.6 kB
1
Indexable
Never
const chai = require('chai');
const sinon = require('sinon');
const sinonChai = require('sinon-chai');
const chaiHttp = require('chai-http');

const { expect } = chai;
const productsServices = require('../../../src/services/products.services');
const productController = require('../../../src/controllers/products.controller');

chai.use(chaiHttp);
chai.use(sinonChai);

const PRODUCTS_MOCK = [      
  { id: 1, name: 'Martelo de Thor' },
  { id: 2, name: 'Traje de encolhimento' },
  { id: 3, name: 'Escudo do Capitão América' },
];

const SERVICES_MOCK = {
  status: 200,
  data: PRODUCTS_MOCK,
};

const SERVICES_MOCK_NOTFOUND = {
  message: 'Product not found',
};

describe('Tests /models/products.controller', function () {
  afterEach(function () {
    sinon.restore();
  });

  describe('When products/product exists', function () {
    it('Returns all the products from the table PRODUCTS as an array', async function () {
      const req = {
        params: {
          id: 1,
        },
      };
      const res = {
        status: sinon.stub().returnsThis(),
        json: sinon.stub().returnsThis(),
      };
      const stub = sinon.stub(productsServices, 'getProducts').resolves(SERVICES_MOCK);
      await productController.getAllProducts(req, res);
      expect(res.status).to.have.been.calledWith(200);
      stub.restore();
    });
  
    it('Returns a single product when the ID is found in the table PRODUCTS', async function () {
      const SINGLE_PRODUCT_MOCK = { 
        id: 1,
        name: 'Martelo de Thor',
      };
      const res = {
        status: sinon.stub().returnsThis(),
        json: sinon.stub().returnsThis(),
      };
      const req = {
        params:
        {
          id: 1,
        },
      };
      const stub = sinon.stub(productsServices, 'getProductId').resolves(SINGLE_PRODUCT_MOCK);
      await productController.getProductsByID(req, res);
      expect(res.status).to.have.been.calledWith(200);
  
      stub.restore();
    });
  });

  describe('When products/product DOES NOT exists', function () {
    it('Returns "Product not found" if an product does not exist in the table PRODUCTS', async function () {
      const res = {
        status: sinon.stub().returnsThis(),
        json: sinon.stub().returnsThis(),
      };
      const req = {
        params:
        {
          id: 1,
        },
      };
      const stub = sinon.stub(productsServices, 'getProductId').resolves(SERVICES_MOCK_NOTFOUND);
      await productController.getProductsByID(req, res);
  
      expect(res.status).to.have.been.calledWith(200);
      stub.restore();
    });
  });
});
Leave a Comment