Jest Cheatsheet

spyOn modules

// myModule.ts export function foo () { return true }
// anotherModule.spec.ts import * as myModule from './myModule' const spyOnMyModule = jest.spyOn(myModule, 'foo') spyOnMyModule.mockReturnValue(true)

模擬 HTMLElement 部分屬性

const table = document.createElement('div');
const mockTableSetScrollTop = jest.fn()

Object.defineProperty(table, 'scrollTop', {
  get: () => 500,
  set: mockTableSetScrollTop,
});

檢查函式呼叫帶的參數是否部分匹配

import * as myModule from '...' const spyOnMyModule = jest.spyOn(myModule, 'foo') // Method 1: expect( spyOnMyModule.mock.lastCall[0] ).toMatchObject({ ... }); // Method 2: expect( spyOnMyModule.mock.call[0][0] ).toMatchObject({ ... }); // Method 3: expect(spyOnMyModule).toBeCalledWith( expect.objectContaining({ ... }) );

留意多個 describe() 之間的執行順序

describe('describe A', () => { console.log('1') beforeAll(() => console.log('3')) }) describe('describe B', () => { console.log('2') beforeAll(() => console.log('4')) })

執行順序:1 → 2 → 3 → 4

describe 區塊直接呼叫 jest.spyOn(),可能會導致後面的 describe B 把前面 describe A 的給覆蓋掉。

測試元素的某個方法有無被呼叫

it('should scroll to end', async () => { const mockScrollTo = jest.fn(); window.HTMLElement.prototype.scrollTo = mockScrollTo; const wrapper = mount(App); wrapper.vm.scrollToEnd(); expect(mockScrollTo).toBeCalled(); });

計算覆蓋率

jest --coverage 
jest --coverage --collectCoverageFrom=<file-path>

檔案變動時自動重跑測試

jest --watch 
jest --watchAll