Untitled
unknown
plain_text
a year ago
1.9 kB
7
Indexable
typescript import { expect } from 'chai'; import { Request, Response } from 'express'; import sinon from 'sinon'; import { suite, before, after, it } from 'mocha'; import productService from './productService'; // Assume productService is in the same directory import productController from './productController'; suite('productController.getAllProducts', () => { let req: Partial<Request>; let res: Partial<Response>; let statusStub: sinon.SinonStub; let jsonStub: sinon.SinonStub; let productServiceStub: sinon.SinonStub; before(() => { req = {}; res = { status: sinon.stub(), json: sinon.stub(), }; statusStub = res.status as sinon.SinonStub; statusStub.returns(res); jsonStub = res.json as sinon.SinonStub; productServiceStub = sinon.stub(productService, 'getAllProducts'); }); after(() => { sinon.restore(); }); it('should retrieve all products and return a 200 status code with the product list', async () => { const fakeProducts = [{ id: 1, name: 'Test Product' }]; productServiceStub.resolves(fakeProducts); await productController.getAllProducts(req as Request, res as Response); expect(statusStub.calledWith(200)).to.be.true; expect(jsonStub.calledWith(fakeProducts)).to.be.true; }); it('should handle errors when productService.getAllProducts throws an error', async () => { const errorMessage = 'Error fetching products'; productServiceStub.rejects(new Error(errorMessage)); try { await productController.getAllProducts(req as Request, res as Response); } catch (error) { expect(error).to.be.instanceOf(Error); expect(error.message).to.equal(errorMessage); } // Optionally assert whether you inform the client of the error // For example, if your error handling would call res.status(500).json(...) }); });
Editor is loading...
Leave a Comment