Developing and testing service functions
Up until now, we have always been testing code by putting it in the src/example.js
file. Now, we are going to write some service functions and learn how to write actual tests for them by using Jest.
Setting up the test environment
First, we are going to set up our test environment by following these steps:
- Install
jest
andmongodb-memory-server
as dev dependencies:$ npm install --save-dev jest@29.7.0 \ mongodb-memory-server@9.1.1
Jest is a test runner used to define and execute unit tests. The
mongodb-memory-server
library allows us to spin up a fresh instance of a MongoDB database, storing data only in memory, so that we can run our tests on a fresh database instance. - Create a
src/test/
folder to put the setup for our tests in. - In this folder, create a
src/test/globalSetup.js
file, where we will importMongoMemoryServer
from the previously installed library:import { MongoMemoryServer } from 'mongodb-memory...