Your First Test
Learn to write your first test in this lesson.
We'll cover the following
Writing a test
Time for your first test. Create a file called greeting.test.js
:
// greeting.test.js
const greeting = guest => `Hello, ${guest}!`;
describe('greeting()', () => { // 1
it('says hello', () => { // 2
expect(greeting('Jest')).toBe('Hello, Jest!'); // 3
});
});
describe()
declares a test suite, which is a grouping of tests. Its first argument is a name, and the second is a function containing one or more tests.it()
declares a test. Its first argument is a name, and the second is a function with the actual test code.expect()
creates an assertion. It takes a single argument, typically a value generated by the code being tested, and returns an object that exposes a set of matcher functions.toBe()
a matcher that performs a strict equality test between the value being tested (theexpect()
argument) and the expected value (its own argument).
Note the grammatical convention here: the test suite name ("greeting()"
) is a noun. The test name ("says hello"
) is a verb. Together, they form a complete sentence describing the functionality covered by the test ("greeting() says hello"
). This convention helps make test output easy to read. You can learn more about all of these methods in the Jest API docs.
To run the test, all you need to do is invoke the jest
CLI. By default, it finds and runs every file in the current project with the .test.js
extension. Since you set jest
as the test
script in package.json
, you can run it with npm run test
:
$ npm test
...
PASS ./greeting.test.js
greeting()
✓ says hello (3ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.83s
Ran all test suites.
Excellent! Jest found the test file, ran the test, and confirmed that greeting('Jest')
produces the string 'Hello, Jest!'
.
You can go ahead and delete greeting.test.js
. In the next section, we’ll start building this chapter’s project.
We have filled the
greetings.test.js
file for you below, now try to run the test usingnpm test
.
Get hands-on with 1400+ tech skills courses.