Vai al contenuto principale
{ "message": "Versione: 30.0", "description": "" }

Manipolazione del DOM

Traduzione Beta Non Ufficiale

Questa pagina è stata tradotta da PageTurner AI (beta). Non ufficialmente approvata dal progetto. Hai trovato un errore? Segnala problema →

Un'altra categoria di funzioni spesso considerata difficile da testare è il codice che manipola direttamente il DOM. Vediamo come testare il seguente frammento di codice jQuery che ascolta un evento click, recupera alcuni dati in modo asincrono e imposta il contenuto di un elemento 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);
});
});

Ancora una volta, creiamo un file di test nella cartella __tests__/:

__tests__/displayUser-test.js
'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');
});

Stiamo simulando fetchCurrentUser.js in modo che il nostro test non effettui una vera richiesta di rete, ma risolva invece con dati simulati localmente. Ciò garantisce che il nostro test possa completarsi in millisecondi invece che in secondi e assicura una velocità di iterazione rapida per i test unitari.

Inoltre, la funzione in fase di test aggiunge un event listener sull'elemento DOM #button, quindi dobbiamo configurare correttamente il nostro DOM per il test. jsdom e il pacchetto jest-environment-jsdom simulano un ambiente DOM come se fossimo in un browser. Ciò significa che ogni API DOM che chiamiamo può essere osservata nello stesso modo in cui verrebbe osservata in un browser!

Per iniziare con l'ambiente di test JSDOM, il pacchetto jest-environment-jsdom deve essere installato se non è già presente:

npm install --save-dev jest-environment-jsdom

Il codice per questo esempio è disponibile presso examples/jquery.