Loading...
Loading...
Jest testing best practices for JavaScript and TypeScript applications, covering test structure, mocking, and assertion patterns.
npx skill4agent add mindrally/skills jestdescribebeforeEachafterEachbeforeAllafterAlljest.mock()jest.fn()jest.spyOn()jest.clearAllMocks()toEqualtoBetoMatchSnapshotwaitFor--coveragedescribe('fetchUser', () => {
it('should return user data when API call succeeds', async () => {
const mockUser = { id: 1, name: 'John' };
jest.spyOn(api, 'get').mockResolvedValue(mockUser);
const result = await fetchUser(1);
expect(result).toEqual(mockUser);
expect(api.get).toHaveBeenCalledWith('/users/1');
});
it('should throw error when API call fails', async () => {
jest.spyOn(api, 'get').mockRejectedValue(new Error('Not found'));
await expect(fetchUser(999)).rejects.toThrow('Not found');
});
});