DOM 操作

    displayUser.js

    __tests__/displayUser-test.js

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

    我们mock了 的实现,这样我们的测试就不会产生真正的网络请求,而是使用本地mock的数据。 这确保了我们的测试能够在毫秒级完成,而不是秒,并且保证了快速的单元测试迭代速度。