Untitled
unknown
plain_text
8 months ago
2.4 kB
2
Indexable
Never
// PRODUCTS CONTROLLER TEST import chai, { expect } from 'chai'; import sinon from 'sinon'; import sinonChai from 'sinon-chai'; import { Request, Response } from 'express'; import createProductController from '../../../src/controllers/products.controller'; import productsService from '../../../src/services/products.service'; chai.use(sinonChai); describe('ProductsController', function () { const req = {} as Request; const res = {} as Response; beforeEach(function () { res.status = sinon.stub().returns(res); res.json = sinon.stub().returns(res); sinon.restore(); }); describe('createProductController', function () { it('should create a new product and return the result', async function () { const req = { body: { name: 'Product Name', price: "9.99", userId: 1 } } as Request; const product = { name: 'Product Name', price: "9.99", userId: 1 }; const expectedResult = { id: 1, name: 'Product Name', price: "9.99", userId: 1 }; sinon.stub(productsService, 'createProduct').resolves(expectedResult); await createProductController.createProductController(req, res); expect(res.status).to.be.calledWith(201); expect(res.json).to.be.calledWith(expectedResult); }); }); }); // PRODUCTS SERVICE TESTS import { expect } from 'chai'; import sinon from 'sinon'; import createProduct from '../../../src/services/products.service'; import ProductModel from '../../../src/database/models/product.model'; describe('ProductsService', function () { beforeEach(function () { sinon.restore(); }); describe('createProduct', function () { it('should create a new product', async function () { const product = { name: 'Test Product', price: "10.99", userId: 1, }; const createStub = sinon.stub(ProductModel, 'create').resolves(); const countStub = sinon.stub(ProductModel, 'count').resolves(1); const result = await createProduct.createProduct(product); expect(createStub.calledOnceWith(product)).to.be.true; expect(countStub.calledOnce).to.be.true; expect(result).to.deep.equal({ id: 1, name: product.name, price: product.price, userId: product.userId, }); }); }); });
Leave a Comment