W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
另一類通常被認(rèn)為難以測(cè)試的函數(shù)是直接操作 DOM 的代碼。讓我們看看如何測(cè)試以下用來(lái)偵聽單擊事件、異步獲取一些數(shù)據(jù)并設(shè)置 span 的內(nèi)容的 jQuery 代碼片段。
// 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);
});
});
接著,我們?cè)?__tests__/
?文件夾下創(chuàng)建一個(gè)測(cè)試文件:
// __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).toBeCalled();
expect($('#username').text()).toEqual('Johnny Cash - Logged In');
});
被測(cè)試的函數(shù)在?#buttonDOM
? 元素上添加了一個(gè)事件監(jiān)聽器,所以我們需要為測(cè)試正確設(shè)置我們的 DOM。Jest 附帶?jsdom
?它模擬 DOM 環(huán)境,就像在瀏覽器中一樣。這意味著我們調(diào)用的每個(gè) DOM API 都可以像在瀏覽器中一樣被觀察到!
我們模擬了 ?fetchCurrentUser.js
?的實(shí)現(xiàn),這樣我們的測(cè)試就不會(huì)產(chǎn)生真正的網(wǎng)絡(luò)請(qǐng)求,而是使用本地mock的數(shù)據(jù)。 這確保了我們的測(cè)試能夠在毫秒級(jí)完成,而不是秒,并且保證了快速的單元測(cè)試迭代速度。
這個(gè)例子的代碼可以 examples/jquery找到。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: