5 min read
•Question 37 of 62mediumHow to write tests in Node.js?
Testing Node.js applications with Jest and Mocha.
What You'll Learn
- Testing frameworks
- Writing unit tests
- API testing
Jest
$ terminalBash
npm install -D jestcode.jsJavaScript
// math.js
function add(a, b) { return a + b; }
function multiply(a, b) { return a * b; }
module.exports = { add, multiply };
// math.test.js
const { add, multiply } = require('./math');
describe('Math functions', () => {
test('adds 1 + 2 to equal 3', () => {
expect(add(1, 2)).toBe(3);
});
test('multiplies 2 * 3 to equal 6', () => {
expect(multiply(2, 3)).toBe(6);
});
});Async Tests
code.jsJavaScript
const { fetchUser } = require('./api');
test('fetches user data', async () => {
const user = await fetchUser(1);
expect(user).toHaveProperty('name');
expect(user.id).toBe(1);
});Mocking
code.jsJavaScript
jest.mock('./database');
const db = require('./database');
test('creates user', async () => {
db.save.mockResolvedValue({ id: 1, name: 'John' });
const result = await createUser({ name: 'John' });
expect(db.save).toHaveBeenCalledWith({ name: 'John' });
expect(result.id).toBe(1);
});API Testing with Supertest
$ terminalBash
npm install -D supertestcode.jsJavaScript
const request = require('supertest');
const app = require('./app');
describe('GET /api/users', () => {
it('returns list of users', async () => {
const res = await request(app)
.get('/api/users')
.expect(200);
expect(res.body).toBeInstanceOf(Array);
});
});