Testing


John Alexis Guerra Gómez


Slides:http://johnguerra.co/lectures/webDevelopment_fall2021/11_Testing/

Class page:https://johnguerra.co/classes/webDevelopment_fall_2021/

Readings discussion

  • questions?

Testing

Types of Testing

  • Unit test
  • Integration test
  • Acceptance test (end to end test)
  • Load test

Jest

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

Getting Started

sum.js

function sum(a, b) {
  return a + b;
}
module.exports = sum;

Add a test file

sum.test.js

const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

Add to config

package.json

{
  "scripts": {
    "test": "jest"
  }
}

Run it

yarn test

or

npm run test

What can you match?

https://jestjs.io/docs/en/using-matchers
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);
});

Async calls

e.g. database calls

https://jestjs.io/docs/en/asynchronous
test('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');
});

Setting up

https://jestjs.io/docs/en/setup-teardown
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();
});

Testing the database

Install jest-mongodb

yarn add mongodb
yarn add @shelf/jest-mongodb --dev

package.json

{
  "preset": "@shelf/jest-mongodb"
}

Jest and MongoDB

https://jestjs.io/docs/en/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);
  });
});