Jest DOM操作

2021-09-04 13:45 更新

另一類通常被認為難以測試的函數(shù)是直接操作 DOM 的代碼。讓我們看看如何測試以下用來偵聽單擊事件、異步獲取一些數(shù)據(jù)并設置 span 的內容的 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. });

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

  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. });

被測試的函數(shù)在?#buttonDOM? 元素上添加了一個事件監(jiān)聽器,所以我們需要為測試正確設置我們的 DOM。Jest 附帶?jsdom?它模擬 DOM 環(huán)境,就像在瀏覽器中一樣。這意味著我們調用的每個 DOM API 都可以像在瀏覽器中一樣被觀察到!

我們模擬了 ?fetchCurrentUser.js?的實現(xiàn),這樣我們的測試就不會產(chǎn)生真正的網(wǎng)絡請求,而是使用本地mock的數(shù)據(jù)。 這確保了我們的測試能夠在毫秒級完成,而不是秒,并且保證了快速的單元測試迭代速度。

這個例子的代碼可以 examples/jquery找到。


以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號