📚 Cheatsheet

Une collection organisée de snippets de code pour accélérer votre développement. Parcourez, recherchez et copiez en un clic.

Snippets 10

Retour
Jest - Hooks 'beforeEach' et 'afterEach'
Facile
beforeEach(() => {
  // Initialisation avant chaque test
});

afterEach(() => {
  // Nettoyage après chaque test
});
Jest - Matcher de base 'toBe'
Facile
expect(2 + 2).toBe(4);
Jest - Matcher pour les objets 'toEqual'
Facile
const data = { one: 1 };
data['two'] = 2;
expect(data).toEqual({ one: 1, two: 2 });
Jest - Simuler une fonction (mock)
Intermédiaire
const mockCallback = jest.fn();
maFonction(mockCallback);
expect(mockCallback).toHaveBeenCalled();
Jest - Simuler une implémentation
Avancé
const myMock = jest.fn();
myMock.mockReturnValueOnce(true).mockReturnValueOnce(false);
Jest - Structure d'un test
Facile
describe('maFonction', () => {
  it('devrait retourner true si le nombre est pair', () => {
    expect(maFonction(2)).toBe(true);
  });
});
Jest - Tester la négation '.not'
Facile
expect(1 + 1).not.toBe(3);
Jest - Tester les exceptions
Intermédiaire
function compileAndroidCode() {
  throw new Error('you are using the wrong JDK');
}

it('compiling android goes as expected', () => {
  expect(() => compileAndroidCode()).toThrow('you are using the wrong JDK');
});
Jest - Tester les valeurs booléennes
Facile
expect(myVar).toBeTruthy();
expect(myVar).toBeFalsy();
Jest - Tester un composant React (avec RTL)
Intermédiaire
import { render, screen } from '@testing-library/react';

it('renders a heading', () => {
  render(<MyComponent />);
  const heading = screen.getByRole('heading', { name: /Bonjour/i });
  expect(heading).toBeInTheDocument();
});