Jest DOM操作

2021-09-04 13:45 更新

另一類通常被認(rèn)為難以測(cè)試的函數(shù)是直接操作 DOM 的代碼。讓我們看看如何測(cè)試以下用來(lái)偵聽單擊事件、異步獲取一些數(shù)據(jù)并設(shè)置 span 的內(nèi)容的 jQuery 代碼片段。

  1. // displayUser.js
  2. 'use strict';
  3. const $ = require('jquery');
  4. const fetchCurrentUser = require('./fetchCurrentUser.js');
  5. $('#button').click(() => {
  6. fetchCurrentUser(user => {
  7. const loggedText = 'Logged ' + (user.loggedIn ? 'In' : 'Out');
  8. $('#username').text(user.fullName + ' - ' + loggedText);
  9. });
  10. });

接著,我們?cè)?__tests__/?文件夾下創(chuàng)建一個(gè)測(cè)試文件:

  1. // __tests__/displayUser-test.js
  2. 'use strict';
  3. jest.mock('../fetchCurrentUser');
  4. test('displays a user after a click', () => {
  5. // Set up our document body
  6. document.body.innerHTML =
  7. '<div>' +
  8. ' <span id="username" />' +
  9. ' <button id="button" />' +
  10. '</div>';
  11. // This module has a side-effect
  12. require('../displayUser');
  13. const $ = require('jquery');
  14. const fetchCurrentUser = require('../fetchCurrentUser');
  15. // Tell the fetchCurrentUser mock function to automatically invoke
  16. // its callback with some data
  17. fetchCurrentUser.mockImplementation(cb => {
  18. cb({
  19. fullName: 'Johnny Cash',
  20. loggedIn: true,
  21. });
  22. });
  23. // Use jquery to emulate a click on our button
  24. $('#button').click();
  25. // Assert that the fetchCurrentUser function was called, and that the
  26. // #username span's inner text was updated as we'd expect it to.
  27. expect(fetchCurrentUser).toBeCalled();
  28. expect($('#username').text()).toEqual('Johnny Cash - Logged In');
  29. });

被測(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找到。


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)