Getting To Know Jest
Getting To Know Jest
Introduction to Jest
Matchers in Jest
Mock Functions
Jest is a JavaScript unit testing framework, maintained by Facebook that lets you define
your unit tests.
Features of Jest
Mocking
Jest is Fast!
Runs tests parallelly in processes to minimize test runtime.
Runs previously failed tests first.
Automatically finds tests related to changed files.
Easy to set up JavaScript testing solution.
Provides Test isolation i.e. no two tests will ever conflict with each other.
Jest works well with other testing libraries (example Enzyme, Chai).
Installing Jest
Or via yarn:
function sum(a, b) {
return a + b;}
module.exports = sum;
Create sum.test.js file. Let us get started by writing a test for the above function:
expect(sum(1,2)).toBe(3);
});
Note: To create files, run the command touch <<filename>> in Katacoda terminal.
jest
Run only the tests that were stipulated with a pattern or filename:
Voila!!! You just triumphantly wrote your first test using Jest!
Quick Fact
A simple To-do List Application has a lot of features to help you keep track of your daily
commitments - Anywhere. Anytime.
Let us test the javascript To-do List Application that has the following functions:
addTask
updateTask
closeTask
deleteTask
You can refer the To-do List JavaScript functions in Codepen and can make use of that when
you try to write tests on your own.
Introduction to Matchers
Common Matchers
Truthiness
Numbers
Strings
Arrays
Exceptions etc.
Common Matchers
Jest uses toBe and toEqual matchers to test a value is with exact equality.
```sh
expect(2 + 2).toBe(4);
});
```
```sh
test('obj assignment', () => {
data['two'] = 2;
});
```
Truthiness
Sometimes you need to differentiate undefined, null, and false, but in some case, no need
to treat these differently.
Here are the helpers that let you be explicit about what you want.
toBeNull matches only null
toBeUndefined matches only undefined
toBeDefined: opposite of toBeUndefined
toBeTruthy matches anything that an if statement treats as true
toBeFalsy matches anything that an if statement treats as false
test('zero', () => {
const z = 0;
expect(z).not.toBeNull();
expect(z).toBeDefined();
expect(z).not.toBeUndefined();
expect(z).not.toBeTruthy();
expect(z).toBeFalsy();
});
const value = 1 + 1;
expect(value).toBeGreaterThan(3);
});
Here the test fails, because the sum is not greater than 3.
expect(value).toBeCloseTo(0.3); //works.
});
String Matcher
You can check strings against regular expressions with toMatch.
expect('Fresco Play').not.toMatch(/I/);
});
Array Matcher
Jest allows you to check if an array contains a particular item using toContain:
var employee=[];
employee=['Johns', 'Liani'];
expect(employee).toContain('Johns');
});
Exceptions
Use toThrow, if you want to test that a particular function throws an error when it is called.
Here is a sample test that shows four different ways of checking if a function throws an Error.
var employee= [];
function EmptyCheck() {
expect(EmptyCheck).toThrow();
expect(EmptyCheck).toThrow(Error);
expect(EmptyCheck).toThrow('Empty Array');
});
Sometimes while writing tests, you have some setup work that has to happen before tests
run, and you have some finishing work that needs to happen after test run. Jest provides
some helper functions to handle this. Some of them are,
beforeEach and afterEach
beforeAll and afterAll
describe
beforeEach(()=>{
getData();
});
afterEach(()=>{
clearData();
});
test('John: Logins',()=>{
expect(Login('John','**pswd**')).toBeTruthy();
});
test('Liani: Logins',()=>{
expect((Login('Liani','**pswd**')).toBeTruthy();
});
One-Time Setup
In some cases, you only need to do setup once, toward the start of a file. This can be
particularly annoying when the setup is asynchronous, so you cannot just do it inline. Jest
provides beforeAll and afterAll to deal with this circumstance.
beforeAll(()=>{
return initializeDB();
});
afterAll(()=>{
return releaseDB();
});
expect(checkEmployee('John')).toBeTruthy();
});
expect(getExperience('Liani')).toBeGreaterThan('2');
});
Scoping
You can group tests together using a describe block. When they are inside a describe block,
the before and after blocks only apply to the tests within that describe block.
Scoping: An Example
For example, let us say we had not just a Cloud database, but also a Local database. We
could do a different setup for different tests:
beforeAll(() => {
return initializeCloudDB();
});
expect(isConnected('CloudDB')).toBeTruthy();
});
beforeEach(() => {
return initializeLocalDB();
});
expect(UpdateLocalDB('LocalDB','CloudDB')).toBe(true);
});
});
General Advice
If a test fails, the first thing that you have to check is whether the test is failing when it is the
only test that runs.
In Jest, it is simple to run only one test - just temporarily change that test command to
atest.only:
expect(true).toBe(false);
});
function myFun(){
return "myFun called";
mockedFun = jest.genMockFn();
mockedFun.mockImplementation(function () {
});
console.log(mockedFun());
});
.mock property
All mock functions have the special property called .mock, the place where all information
about how the function that has been called is kept.
These mock members are very useful in tests to assert how these functions get called, or
instantiated:
console.log(mockFn.mock.instances.length); // is 1
});
mock.calls
mock.instances
mockClear()
mockReset()
mockRestore()
mockImplementation(fn) and mockImplementationOnce(fn)
mockReturnValue(val) and mockReturnValueOnce(val)
mock.calls array
Jest records all calls that have been made during mock function.
Each call is represented by an array of arguments that were passed during the call.
For example, a mock function f is called twice, with the arguments f(arg1, arg2), and then
with the arguments f(arg3, arg4) would have a mock.calls array like below:
[ [arg1,arg2],
[arg3,arg4], ];
mock.instances array
An array that records all the object instances that have been instantiated from the
mock function using new.
Below example has a mock function that has been instantiated twice.
});
mockRestore()
Will Remove the mock and restores the initial implementation.
Helpful when you have to mock functions in particular test cases and restore the
original implementation in others.
Only works when mock was created with jest.spyOn. Thus you have to take care of
restoration yourself when manually assigning jest.fn().
return "real";
mocked = jest.genMockFn();
mocked.mockImplementation(function () {
return "mocked";
});
mocked.mockImplementationOnce(function () {
return "mocked_once";
});
console.log(real()); //real
console.log(mocked()); //mocked_once
});
test('Mock Returns',()=>{
.mockReturnValue('mocked return');
});
But, when you execute an Asynchronous Code, it will move on to another task before it
finishes.
Callbacks
Promises etc.
function fetchData(callback) {
setTimeout(function () {
callback({status: 'completed'});
}, 2000);
Jest will wait until the done callback is called before finishing the test.
function callback(data) {
expect(data.status).toBe('completed');
done();
fetchData(callback);
});
Above test checks the status of fetchData function. You can also change the status in order
to understand the concept better.
function first() {
setTimeout(function() {
console.log('first');
resolve('first');}, 2000);
});
return promise;
function second() {
setTimeout(function() {
console.log('second');
resolve('second');}, 2000);
});
return promise;
};
expect(first()
.then(second)
.resolves.toBe('second');
});
function second() {
setTimeout(function() {
console.log('second');
});
return promise;
};
expect(first()
.then(second)
.rejects.toBe('error');
});
If you are just getting started with React, we recommend you to go through the
course ReactJS first.
cd my-app
npm start
//index.html
<div id="root">
<!-- This element's contents will be replaced with your component. -->
</div>
//index.js
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
```sh
Quick Fact
Enzyme is a JavaScript Testing utility for React that makes it easier to assert, manipulate,
and traverse a React Component's output.
```sh
```
Why Enzyme?
Front end code behaviors in your UI should also be tested as well in React applications.
//welcome.jsx
return (
<div>Hello world</div>
);
Why Enzyme?
The test for the Welcome component using Enzyme is shown below.
describe('Welcome', () => {
expect(welcome.find('div').text()).toEqual('Hello world');
});
});
Snapshot tests are a useful tool whenever you want to make sure your UI does not change
unexpectedly.
In contrast to a program with low code coverage, a program with high code coverage in %,
has a lower chance of featuring undetected software bugs.
jest --coverage
calc.js
calc.test.js
test('add:1+2=3',()=>{
expect(add(1,2)).toBe(3);
});
But the code coverage gives a test coverage of 50% and ensures that your tests are testing
your code or not.
You can use coverage reports to identify critical misses in our unit tests.
In this scenario, the Code Coverage is the ideal approach to motivate the developers to write
more unit tests to avoid the chances of getting errors after integration.
Code Coverage in Continuous Integration...
Ideally, the CI pipeline should have a code coverage target of 100%, that is the entire
application code is covered by unit tests.
The build can be set to fail if the coverage did not match the required threshold.
Course Summary
In this course you have read:
Introduction to Jest
Getting Started with Jest
Matchers in Jest
Setup and Teardown
Mock Functions
Testing Asynchronous Code
Testing React Apps
If you want to get in deep with Jest, the better to place to start is Jest-Delightful JavaScript
Testing.
Quiz
1. Jest is maintained by ______________ . FACEBOOK
2. Jest works well with other testing libraries like ______________. ALL
3. Jest is used to test _____________. JAVASCRIPT
4. How to install Jest using npm? NPM INSTALL--SAVE-DEV TEST
5. Jest is a JavaScript unit testing framework. T
6. The number can be compared using __________. ALL
7. ______________ matcher matches only undefined. TO BE UNDEFINED
8. Jest uses ________ and ________ matchers to test a value is with exact equality. TO BE, TO
EQUAL
9. The below test will pass.
10. Jest records all calls that have been made during mock function and it is stored
in ______________ array. MOCK.CALLS
11. ______________ resets all information stored in the mockFn.mock.calls and mockFn.mock.instances
arrays. MOCK CLEAR
12. .mock is a property of mock function, the place where all information about how the function has been
called is kept. T
13. Jest supports ______________ for Isolating functionality into small, testable units under test. MOCK
FUNCTIONS
14. Jest will wait until the ______________ callback is called before finishing the test. DONE
15. When you execute ______________ Code, it will move on to another task before it finishes.
ASYNCHRONOUS
16. Snapshot tests are a useful tool whenever you want to make sure your UI does not change
unexpectedly. T
17. The Asynchronous code will move on to another task before it finishes. T
18. Code coverage tests that how much code is covered under tests. T
19. mockRestore() works only when mock was created with ______________. jest.spyOn
20. ______________ is an array that records all the object instances that have been instantiated from the
mock function using new. MOCK.INSTANCES
21. mockRestore() removes the mock and restores the initial implementation. T
22. What is the command to install Jest and the babel-jest ? npm install --save-dev jest
23. Snapshot Testing is not supported in Jest. F
24. How to run your test in terminal? NPM-RUN TEST
25. const value = 0.1 + 0.2; F
26. expect(value).toBe(0.3);
27. The matcher toContain is used _________. ARRAY
28. ______________ is useful when you want to completely restore a mock back to its initial state.
mockReset()
29. To test a particular function which throws an error when it's called, you can usetoThrow.T
30. .mock is a property of mock function, the place where all information about how the function has been
called is kept. T
31. Jest is used by ______________. All of these
32. For Code Coverage Support Jest requires some additional setup and libraries . F
33. ______________ resets all information stored in the mock, including any inital implementation given.
MOCK RESTORE
34. ______________ returns the value only once when mock function is called.
MOCKRETURNVALUEONCE(VALUE)
35. Which method is useful to clean up a mock's usage data between two assertions. MOCK CLEAR
36. If you expect a promise to be rejected, use the ______________ matcher. If the promise is fulfilled, the
test will automatically fail. REJECT
37. ______________ recursively checks every field of an object or array. TO EQUAL
38. The Synchronous Code will move on to another task before it finishes. F
39. How to install Jest using yarn? YARN ADD--DEV JEST
40. ______________ matcher matches only undefined. toBeUndefined
41. To create a mock function, we use jest.fn(). T
42. ______________ recursively checks every field of an object or array. toEqual
43. ______________ is useful when you want to mock functions in certain test cases and restore the
original implementation in others. mockRestore()
44. mockRestore() removes the mock and restores the initial implementation T