Skip to content

Instantly share code, notes, and snippets.

@andersonssantana
Last active March 6, 2023 20:46
Show Gist options
  • Save andersonssantana/d1f0141b27212cc31d0ecbd3989c811f to your computer and use it in GitHub Desktop.
Save andersonssantana/d1f0141b27212cc31d0ecbd3989c811f to your computer and use it in GitHub Desktop.
Mock Jest
it('deve exibir o cartão do pokemon quando clicar no botão de pesquisa', async () => {
const mockData = {cards: [{name: 'Ander', types: ['Teste', 'Mockado'], imageUrl: 'https://avatars.githubusercontent.com/u/69821675?v=4'}]}
// Mock simples com spyOn
jest.spyOn(global, 'fetch').mockResolvedValue({
json: jest.fn().mockResolvedValue(mockData)
});
// Mock duplo com spyOn
jest.spyOn(global, 'fetch')
.mockResolvedValueOnce({
json: jest.fn().mockResolvedValue(mockData1)
})
.mockResolvedValue({
json: jest.fn().mockResolvedValue(mockData2)
});
// Mock usando jest.fn() com mockResolvedValue
global.fetch = jest.fn().mockResolvedValue({
json: jest.fn().mockResolvedValue(mockData)
});
// Mock usando jest.fn() com mockResolvedValue substituindo a implementação
global.fetch = jest.fn(async function() {
return {json: async function() {
return mockData
}}
}
);
// Mock sobrescrevendo a implementação do global.fetch
global.fetch = async function() {
return {json: async function() {
return mockData
}}
}
// Mockando a implementação com múltiplos endpoints:
const fetch = (url) => Promise.resolve({
status: 200,
ok: true,
json: () => {
if (url === 'https://primeiroendpoint')
return Promise.resolve(mockData1);
if (url === 'https://segundendpoint')
return Promise.resolve(mockData2);
},
});
jest.spyOn(global, 'fetch').mockImplementation(fetch);
///////////////////////////
render(<App />);
const input = screen.getByRole('textbox');
userEvent.type(input, 'charmander');
const botao = screen.getByRole('button', { name: /pesquisar/i });
userEvent.click(botao);
expect(global.fetch).toHaveBeenCalled();
expect(global.fetch).toHaveBeenCalledTimes(1);
const tituloDoPokemon = await screen.findByRole('heading', { level: 3, name: /mockzés/i });
expect(tituloDoPokemon).toBeInTheDocument();
jest.restoreAllMocks();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment