Jest
- React Native course
- Intermediate
- Lesson 94/116
- 5 min
Learn the Jest test framework.
What is Jest?
Jest is the test runner that ships with React Native. It provides test() and expect(); you run all tests with npm test. Tests live in the __tests__ folder and use the .test.js suffix.
A test has three parts: a name, a function, and an expected result. test('two plus two', () => { expect(2 + 2).toBe(4); }). expect takes a value; matchers like .toBe compare it. If the match fails Jest shows red. This catches small logic errors early.
test and expect
test(name, fn) defines a test; the first parameter is the test name, the second is the test function. expect(value) takes a value for checking; then matchers like .toBe(value) or .toEqual(value) compare it.
For example expect(result).toBe(4) expects result to equal 4. .toEqual does a deep comparison of objects; .toBe is used for primitives. Multiple expect calls can run in one test; the test stops at the first failure. describe groups related tests; this keeps big test files organized.
Practice Write your first test
Write a test that checks two plus two equals four. Use test('two plus two', () => { ... }); put expect(2 + 2).toBe(4) inside.
Starter code
// Write a test named 'two plus two'
// Use expect with 2 + 2 and toBe 4Sample solution
test('two plus two', () => {
expect(2 + 2).toBe(4);
});Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is Jest's job?
test('toplama', () => { expect(1 + 1).toBe(2); });- Compile the app
- Run tests Correct answer
- Build an APK
- Pick colors
Explanation: Jest runs tests and reports the result.
2 The expect call
test('iki artı iki', () => {____(2 + 2).toBe(4); });
test('iki artı iki', () => {expect(2 + 2).toBe(4); });
Explanation: expect takes the value to check.
3 Match each concept to its role
| Term | Meaning |
|---|---|
test |
Defines a test |
expect |
Takes a value |
.toBe |
Equality check |
describe |
Groups tests |