Manipulação DOM
Outra classe de funções que é frequentemente considerada difícil de testar é o código que manipula diretamente o DOM. Vamos ver como podemos testar o seguinte trecho de código jQuery, que escuta um evento de clique, busca alguns dados de forma assíncrona e define o conteúdo de um span.
'use strict';
const $ = require('jquery');
const fetchCurrentUser = require('./fetchCurrentUser.js');
$('#button').click(() => {
fetchCurrentUser(user => {
const loggedText = 'Logged ' + (user.loggedIn ? 'In' : 'Out');
$('#username').text(user.fullName + ' - ' + loggedText);
});
});
Again, we create a test file in the __tests__/ folder:
'use strict';
jest.mock('../fetchCurrentUser');
test('displays a user after a click', () => {
// Set up our document body
document.body.innerHTML =
'<div>' +
' <span id="username" />' +
' <button id="button" />' +
'</div>';
// This module has a side-effect
require('../displayUser');
const $ = require('jquery');
const fetchCurrentUser = require('../fetchCurrentUser');
// Tell the fetchCurrentUser mock function to automatically invoke
// its callback with some data
fetchCurrentUser.mockImplementation(cb => {
cb({
fullName: 'Johnny Cash',
loggedIn: true,
});
});
// Use jquery to emulate a click on our button
$('#button').click();
// Assert that the fetchCurrentUser function was called, and that the
// #username span's inner text was updated as we'd expect it to.
expect(fetchCurrentUser).toHaveBeenCalled();
expect($('#username').text()).toBe('Johnny Cash - Logged In');
});
We are mocking fetchCurrentUser.js so that our test doesn't make a real network request but instead resolves to mock data locally. Isso garante que nosso teste pode ser concluído em milissegundos, em vez de segundos e garante uma rápida iteração de teste unitário.
Also, the function being tested adds an event listener on the #button DOM element, so we need to set up our DOM correctly for the test. jsdom and the jest-environment-jsdom package simulate a DOM environment as if you were in the browser. This means that every DOM API that we call can be observed in the same way it would be observed in a browser!
To get started with the JSDOM test environment, the jest-environment-jsdom package must be installed if it's not already:
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev jest-environment-jsdom
yarn add --dev jest-environment-jsdom
pnpm add --save-dev jest-environment-jsdom
bun add --dev jest-environment-jsdom
The code for this example is available at examples/jquery.