Testing your code

Two big categories

1. Unit testing

2. End to end testing

and everything in between

Unit testing

why do we write tests?

  • for making sure our code works in the future
  • makes refactoring a breeze
  • helps us find edge cases while writing code

Unit testing

main concepts:

🫁 anatomy of an unit test

👻 mocking

🕵️ spying 

🫁 anatomy of an unit test

beforeEach(() => {});

beforeAll(() => {
  // init something here
  // mock something here
});


afterEach(() => {});

afterAll(() => {
  // clean up here
  // teardown here
});

describe('sum', () => {
    it('should add two numbers', () => {
      const input = sum(1, 2);
      const expectedOutput = 3;
        
      expect(input).toBe(expectedOutput);
    });
});

"lifecycle hooks"

describing the unit of code we test

human readable description of what we want to test

a clear input and output

matcher

👻 mocking

mocking is a technique with which we can replace parts of an application to simulate certain situations or just simply isolate a pice of code from unwanted dependencies.

👻 mocking

const APIService = {
  get(url) {
    return fetch(url);
  },
};
function UserModel(apiService) {
  return {
    data: {
      error: null,
      user: null,
    },

    async getUser(id) {
      try {
        this.user = await apiService.get(`/api/users/${id}`);
      } catch {
        this.error = "💩";
      }
    },
  };
}

👻 mocking

import UserModel from '...';

const buildFakeApiService = getResponse => ({
  get: () => Promise.resolve(getResponse)
});

describe('UserModel', () => {
  it('should store the fetch response on the user key', async () => {
    const user = { name: 'hello' };
    const fakeApiService = buildFakeApiService(user);
    
    const userModel = UserModel(fakeApiService);
    await userModel.get(100);
    
    expect(userModel.user).toEqual(user);
  });
});

🕵️ spying

similar with mocking, but more James Bondy

🕵️ spying

const callMeMaybe = callback => {
  callback('Hey I just met you and this is crazy!')
}
describe('callMeMaybe', () => {
  it('should call me', () => {
    const callbackSpy = jest.fn(); // Our spy function, aka James Bond
    
    callMeMaybe(callbackSpy); // sending in James Bond
    
    expect(callbackSpy).toHaveBeenCalled();
  });
});

Teting react components

react testing library

https://testing-library.com/docs/react-testing-library/example-intro

End to end testing

cypressjs

Unit Testing

testing your code

By Andrei Cacio

testing your code

  • 924