Skip to main content
Version: 27.0

Manipulación del DOM

Another class of functions that is often considered difficult to test is code that directly manipulates the DOM. Let's see how we can test the following snippet of jQuery code that listens to a click event, fetches some data asynchronously and sets the content of a span.

// displayUser.js
'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);
}); 'In' : 'Out');
$('#username').text(user.fullName + ' - ' + loggedText);

Una vez más, creamos un archivo de test en la capeta __tests__ /:

// __tests__/displayUser-test.js
'use strict';
test('displays a user after a click', () => {
// Set up our document body
document.body.innerHTML =
'<div>' +
' <span id="username" />' +
' <button id="button" />' +
// This module has a side-effect
const $ = require('jquery');
const fetchCurrentUser = require('../fetchCurrentUser');
// Tell the fetchCurrentUser mock function to automatically invoke
// its callback with some data
fetchCurrentUser.mockImplementation(cb => {
fullName: 'Johnny Cash',
loggedIn: true,
// Use jquery to emulate a click on our button
// Assert that the fetchCurrentUser function was called, and that the
// #username span's inner text was updated as we'd expect it to.
expect($('#username').text()).toEqual('Johnny Cash - Logged In');

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. Jest ships with jsdom which simulates 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!

Estamos mockeando fetchCurrentUser.js para que nuestro test no haga una solicitud de red real pero en su lugar mockeamos los datos a nivel local. Esto garantiza que nuestro test puede terminar en milisegundos en lugar de segundos y garantiza una rápida interacción en cada unidad de test.

El código de este ejemplo está disponible en: examples/jquery.