Skip to content

Back End Testing

Jenna Kumar edited this page Mar 24, 2021 · 7 revisions

Unit Testing

Libraries

Jest and Supertest are used for unit testing the API endpoints

For more information see: https://www.rithmschool.com/courses/intermediate-node-express/api-tests-with-jest
https://jestjs.io/docs/25.x/mock-functions

Running tests

npm test

Creating tests

Test files must be named like: name.test.js

Firebase instances and Firebase RealTime database instances should be mocked.
An example of mocking a firebase instance is:

// mockFirebase.js

const mockFirebase = {
  auth: jest.fn(() => (mockAuthObject)),
  initializeApp: jest.fn(({}) => ({})) 

}

module.exports = mockFirebase;

To inject this mock when test scripts are ran, see the following example:

// signup.test.js

jest.mock('firebase', () => {
    const {mockFirebase} = require("../test_utils/mocks/mockFirebase")
    return mockFirebase
});

Function calls on this mock object can be tested:

//signup.test.js

 it("when a valid email and password is given it returns 201 and makes calls to firebase", async () => {
        const response = await request(app).post('/signup')
        .set("Accept", "application/json")
        .send(validPasswordAndEmailInput)

        expect(response.status).toBe(201);
        expect(response.body).toEqual(mockToken);

        //tests firebase method calls for creating a user
        expect(firebase.auth).toHaveBeenCalled();
        expect(firebase.auth().createUserWithEmailAndPassword)
        .toHaveBeenCalledWith(validPasswordAndEmailInput.email, validPasswordAndEmailInput.password);

        //tests database calls
        expect(database.ref).toHaveBeenCalledWith('/');
        expect(database.ref().update).toHaveBeenCalledWith({
            [mockUid] : {
                email: validPasswordAndEmailInput.email
            }
        });
    });
Clone this wiki locally