Jest is a popular testing framework for JavaScript. To use it, you will need to have Node.js installed on your machine. Jest provides a simple interface for writing tests and running them.
To write a test, create a new file in the tests
directory with the extension .test.js
. In this file, you will write one or more test cases using Jest's test
function.
test('newNote inserts data and returns it', async () => {
const note = 'Test note';
const tags = ['tag1', 'tag2'];
const data = {
tags,
content: note,
id: Date.now(),
};
insert.mockResolvedValue(data);
const result = await newNote(note, tags);
expect(result).toEqual(data);
});
In the example above, we have a test case that checks whether the newNote
function inserts data into the database and returns it. We first define some test data, and then mock the insert
function to resolve with that data. We then call the newNote
function and use Jest's expect
function to check whether the returned data equals the test data.
To run your tests, use the npm test
command in your terminal. Jest will automatically look for test files in the tests
directory and run them. If you want to run a specific test file, you can use the npm test path/to/test/file
command.
We’re going to write some test using a lib called jest
. Create a tests folder on the root and make a notes.test.js
file.
import { jest } from '@jest/globals';
jest.unstable_mockModule('../src/db.js', () => ({
insert: jest.fn(),
getDB: jest.fn(),
saveDB: jest.fn(),
}));
const { insert, getDB, saveDB } = await import('../src/db.js');
const { newNote, getAllNotes, removeNote } = await import('../src/notes.js');
beforeEach(() => {
insert.mockClear();
getDB.mockClear();
saveDB.mockClear();
})
test('newNote inserts data and returns it', async () => {
const note = 'Test note';
const tags = ['tag1', 'tag2'];
const data = {
tags,
content: note,
id: Date.now(),
};
insert.mockResolvedValue(data);
const result = await newNote(note, tags);
expect(result).toEqual(data);
});
test('getAllNotes returns all notes', async () => {
const db = {
notes: ['note1', 'note2', 'note3']
};
getDB.mockResolvedValue(db);
const result = await getAllNotes();
expect(result).toEqual(db.notes);
});
test('removeNote does nothing if id is not found', async () => {
const notes = [
{ id: 1, content: 'note 1' },
{ id: 2, content: 'note 2' },
{ id: 3, content: 'note 3' },
];
saveDB.mockResolvedValue(notes);
const idToRemove = 4;
const result = await removeNote(idToRemove);
expect(result).toBeUndefined();
});