jguerra[at}northeastern.edu | @duto_guerra
Slides:http://johnguerra.co/lectures/webDevelopment_fall2020/11_Testing/
Class page:http://johnguerra.co/classes/webDevelopment_spring_2020/
Jest is a testing framework (included in create-react-app). We can use it to test js code
yarn add --dev jest
or
npm install --save-dev jest
sum.js
function sum(a, b) {
return a + b;
}
module.exports = sum;
sum.test.js
const sum = require('./sum');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
package.json
{
"scripts": {
"test": "jest"
}
}
yarn test
or
npm run test
test('two plus two', () => {
const value = 2 + 2;
expect(value).toBeGreaterThan(3);
expect(value).toBeGreaterThanOrEqual(3.5);
expect(value).toBeLessThan(5);
expect(value).toBeLessThanOrEqual(4.5);
// toBe and toEqual are equivalent for numbers
expect(value).toBe(4);
expect(value).toEqual(4);
});
e.g. database calls
https://jestjs.io/docs/en/asynchronoustest('the data is peanut butter', () => {
return fetchData().then(data => {
expect(data).toBe('peanut butter');
});
});
test('the data is peanut butter', () => {
return expect(fetchData()).resolves.toBe('peanut butter');
});
beforeAll(() => {
return initializeCityDatabase();
});
afterAll(() => {
return clearCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
yarn add mongodb
yarn add @shelf/jest-mongodb --dev
package.json
{
"preset": "@shelf/jest-mongodb"
}
const {MongoClient} = require('mongodb');
describe('insert', () => {
let connection;
let db;
beforeAll(async () => {
connection = await MongoClient.connect(global.__MONGO_URI__, {
useNewUrlParser: true,
});
db = await connection.db(global.__MONGO_DB_NAME__);
});
afterAll(async () => {
await connection.close();
await db.close();
});
it('should insert a doc into collection', async () => {
const users = db.collection('users');
const mockUser = {_id: 'some-user-id', name: 'John'};
await users.insertOne(mockUser);
const insertedUser = await users.findOne({_id: 'some-user-id'});
expect(insertedUser).toEqual(mockUser);
});
});