import { describe, it } from "mocha";import supertest from "supertest";import { expect } from "chai";import config from "../src/config/config.js";import mongoose, { isValidObjectId } from "mongoose";const requester = supertest(`http://localhost:${config.PORT}`);// Connect to database before testsawait mongoose.connect(config.MONGO_URL, {dbName: config.DB_NAME});
Tests should clean up test data after execution using Mocha’s after hook:
describe("Pruebas router pets", function(){ this.timeout(10_000); after(async()=>{ // Delete all test pets with specie "test" await mongoose.connection.collection("pets").deleteMany({specie:"test"}); }); // Tests...});
it("Si consulto todas las mascotas al endpoint /api/pets metodo GET, me debería devolver un array de mascotas", async() => { let {body} = await requester.get("/api/pets").send(); expect(Array(body.payload));});
Verify that valid requests return expected status codes and data structures:
it("Should create a new resource", async() => { let mockData = { /* valid data */ }; let {status, body} = await requester.post("/api/endpoint").send(mockData); expect(status).to.be.eq(200); expect(body).to.has.property("_id");});
expect(status).to.be.eq(200); // Successexpect(status).to.be.eq(201); // Createdexpect(status).to.be.eq(400); // Bad Requestexpect(status).to.be.eq(404); // Not Foundexpect(status).to.be.eq(500); // Server Error
expect(Array(body.payload)); // Is an arrayexpect(body.payload).to.has.property("_id"); // Has propertyexpect(isValidObjectId(body.payload._id)).to.be.true; // Valid MongoDB ObjectIdexpect(body.message).to.be.eq("Expected message"); // Exact match