Jest is a delightful JavaScript Testing Framework with a focus on simplicity. It works with projects using: Babel, TypeScript, Node, React, Angular, Vue and more!
To install Jest, run the following command:
npm install --save-dev jest
Add the following section to your package.json
:
{
"scripts": {
"test": "jest"
}
}
A basic test in Jest looks like this:
test('description of the test', () => {
// Your test code here
expect(someValue).toBe(expectedValue);
});
You can also use it
instead of test
:
it('should do something', () => {
// Your test code here
});
Jest uses "matchers" to let you test values in different ways. Here are some common matchers:
expect(2 + 2).toBe(4);
expect({name: 'John', age: 30}).toEqual({name: 'John', age: 30});
expect(null).toBeNull();
expect(undefined).toBeUndefined();
expect(true).toBeTruthy();
expect(false).toBeFalsy();
expect(value).toBeGreaterThan(3);
expect(value).toBeGreaterThanOrEqual(3.5);
expect(value).toBeLessThan(5);
expect(value).toBeLessThanOrEqual(4.5);
expect('team').not.toMatch(/I/);
expect('Christoph').toMatch(/stop/);
expect(['Apple', 'Banana', 'Orange']).toContain('Banana');
expect(() => {
throw new Error('You are using the wrong JDK');
}).toThrow();
expect(() => {
throw new Error('You are using the wrong JDK');
}).toThrow('You are using the wrong JDK');
expect(() => {
throw new Error('You are using the wrong JDK');
}).toThrow(/JDK/);
test('the data is peanut butter', () => {
return fetchData().then(data => {
expect(data).toBe('peanut butter');
});
});
test('the data is peanut butter', async () => {
const data = await fetchData();
expect(data).toBe('peanut butter');
});
test('the data is peanut butter', done => {
function callback(data) {
try {
expect(data).toBe('peanut butter');
done();
} catch (error) {
done(error);
}
}
fetchData(callback);
});
test('mock implementation of a function', () => {
const mock = jest.fn(() => 'bar');
expect(mock('foo')).toBe('bar');
expect(mock).toHaveBeenCalledWith('foo');
});
jest.mock('./myModule');
const myModule = require('./myModule');
test('should do something', () => {
myModule.someFunction.mockReturnValue('mocked value');
expect(myModule.someFunction()).toBe('mocked value');
});
jest.useFakeTimers();
test('waits 1 second before ending the game', () => {
const timerGame = require('../timerGame');
timerGame();
expect(setTimeout).toHaveBeenCalledTimes(1);
expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 1000);
});
beforeAll(() => {
// Runs before all tests
});
afterAll(() => {
// Runs after all tests
});
beforeEach(() => {
// Runs before each test
});
afterEach(() => {
// Runs after each test
});
describe('matching cities to foods', () => {
test('Vienna <3 sausage', () => {
expect(isValidCityFoodPair('Vienna', 'Wiener Schnitzel')).toBe(true);
});
test('San Juan <3 plantains', () => {
expect(isValidCityFoodPair('San Juan', 'Mofongo')).toBe(true);
});
});
it('renders correctly', () => {
const tree = renderer
.create(<Link page="http://www.facebook.com">Facebook</Link>)
.toJSON();
expect(tree).toMatchSnapshot();
});
Add the following section to your package.json
:
{
"jest": {
"collectCoverage": true,
"coverageReporters": ["json", "lcov", "text", "clover"]
}
}
Or use the --coverage
flag when running Jest.
Test Description: Write clear and descriptive test names.
Arrange-Act-Assert: Structure your tests using the AAA pattern.
Don't test implementation details: Focus on testing the public API of your modules.
Avoid duplication: Use beforeEach
and afterEach
to avoid repeating setup and teardown code.
Mock external dependencies: Use mocking to isolate the code you're testing.
Keep tests simple: Each test should verify one specific behavior.
Run tests in isolation: Tests should not depend on each other.
Use test.only
for debugging: When debugging, use test.only
to run only one test.
Update snapshots carefully: Always review snapshot changes before updating them.
Continuous Integration: Run your tests as part of your CI/CD pipeline.
2024 © All rights reserved - buraxta.com