and everything in between
why do we write tests?
main concepts:
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 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.
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 = "💩";
}
},
};
}
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);
});
});
similar with mocking, but more James Bondy
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();
});
});
react testing library
https://testing-library.com/docs/react-testing-library/example-intro
cypressjs