Let's create our first unit test in our project to test the required function in Form.tsx:
- Start by creating a file called Form.test.tsx in the src folder. We'll use this file for our test code, to test the code in Form.tsx.
- Let's import the function we want to test, along with a TypeScript type we need for a parameter value:
import { required, IValues } from "./Form";
- Let's start to create our test using the Jest test function:
test("When required is called with empty title, 'This must be populated' should be returned", () => {
// TODO: implement the test
});
The test function takes in two parameters:
- The first parameter is a message telling us whether the test passed or not, which will be shown in the test output
- The second parameter is an arrow function that will contain our test
- We'll move on to calling the required function with a values parameter that contains an empty title property:
test("When required called with title being an empty string, an error should be 'This must be populated'", () => {
const values: IValues = {
title: ""
};
const result = required("title", values);
// TODO: check the result is correct
});
- Our next task in this test is to check that the result from the required function is what we expect. We can use the Jest expect function to do this:
test("When required called with title being an empty string, an error should be 'This must be populated'", () => {
const values: IValues = {
title: ""
};
const result = required("title", values);
expect(result).toBe("This must be populated");
});
We pass the variable we are checking into the expect function. We then chain a toBe matcher function onto this, which checks that the result from the expect function is the same as the parameter supplied to the toBe function.
- Now that our test is complete, we can run the test by typing the following in the terminal:
npm test
This starts the Jest test runner in watch mode, which means that it will continuously run, executing tests when we change the source files.
Jest will eventually find our test file, execute our test, and output the result to the terminal, as follows:
- Let's change the expected result in the test to make the test fail:
expect(result).toBe("This must be populatedX");
When we save the test file, Jest automatically executes the test and outputs the failure to the terminal, as follows:
Jest gives us valuable information about the failure. It tells us this:
- Which test failed
- What the expected result was, in comparison to the actual result
- The line in our test code where the failure occurred
This information helps us quickly resolve test failures.
- Before we move on, let's correct our test code:
expect(result).toBe("This must be populated");
When we save the change, the test should now pass.