Search code examples
javascriptmocha.jssupertest

how to split Mocha.Suite nested functions


How to separate this mocha suite function into 3 different functions? (JavaScript)

describe("User login", function () {
    it("user should login", async function () {
      const response = await request
        .post("userservice/login")
        .send({
            email: "user@mail.com",
            password: "123"
            }); 
            expect(response.status).to.be.eql(200);
    });
});

That I would get something like this:

describe("User login", First());


function First () {
    it("user should login", Second());
  }

async function Second () {
    const response = await request
      .post("userservice/login")
      .send({
          email: "user@mail.com",
          password: "123"
          }); 
          expect(response.status).to.be.eql(200);      
  }

This throws an error:

TypeError: Suite "User login" was defined but no callback was supplied. Supply a callback or explicitly skip the suite.

Apparently, something needs to be passed to the functions, but I can't figure out what (or how).


Solution

  • The second argument of describe and it should be a callback function. But you passed the return value of the First and Second functions. The return value of the First function is undefined, that's why you got the error.

    So it should be:

    const chai = require('chai');
    const { expect } = chai;
    
    describe("User login", First);
    
    function First() {
      it("user should login", Second);
    }
    
    function Second() {
      expect(1 + 1).to.be.eql(2);
    }