mocha.jschaishould.js

How to add custom success message in Mocha tests?


I have a loop inside a test case where I repeat a part of the test for each data sample.

How can I add a custom sucess message indicating that specific data, representing a test case, was sucessful?

For instance, my code is like:

it('Should not allow saving bad data: ', async function () {
  let badData = TestDataProvider.allData.invalid;
  for (let i = 0; i < badData.length; i++) {
    let d = badData[i];
    let res = await request.post('/data').send(d);
    let object = null;
    try {
      object = JSON.parse(res.text);
    } catch (e) {
      object = {};
    }
    expect(res.statusCode).to.equal(206);
    expect(object).not.to.contain.a.property('_id');
    console.log('Verified case: ' + d.testDesc);
  }
});

I want the "Verified case..." message to appear as successful test runs and not console messages in reports.

The testDesc attribute holds test description like: "Missing field a", "Invalid property b", "Missing field c".


Solution

  • I solved the problem creating dynamic tests:

    const allData = JSON.parse(fs.readFileSync('data.json'), 'utf8'));
    allData.invalid.forEach((badData) => {
      it('Should not allow saving with: ' + badData.testDesc, async () => {
        let res = await request.post('/data').send(badData);
        let d = null;
        try {
          d = JSON.parse(res.text);
        } catch (e) {
          d = {};
        }
        expect(res.statusCode).to.equal(206);
        expect(d).not.to.contain.a.property('_id');
      });
    });