When we installed the mocha npm package, it provided us with the mocha command to execute our tests. When we run mocha, it will inject several functions, including describe and it, as global variables into the test environment. The describe function allows us to group relevant test cases together, and the it function defines the actual test case.
Inside index.unit.tests.js, let's define our first describe block:
import assert from 'assert';
import generateValidationErrorMessage from '.';
describe('generateValidationErrorMessage', function () {
it('should return the correct string when error.keyword is "required"', function () {
const errors = [{
keyword: 'required',
dataPath: '.test.path',
params: {
missingProperty: 'property',
},
}];
const actualErrorMessage = generateValidationErrorMessage(errors);
const expectedErrorMessage = "The '.test.path.property' field is missing";
assert.equal(actualErrorMessage, expectedErrorMessage);
});
});
Both the describe and it functions accept a string as their first argument, which is used to describe the group/test. The description has no influence on the outcome of the test, and is simply there to provide context for someone reading the tests.
The second argument of the it function is another function where you'd define the assertions for your tests. The function should throw an AssertionError if the test fails; otherwise, Mocha will assume that the test should pass.
In our test, we have created a dummy errors array that mimics the errors array, which is typically generated by Ajv. We then passed the array into the generateValidationErrorMessage function and capture its returned value. Lastly, we compare the actual output with our expected output; if they match, the test should pass; otherwise, it should fail.