# Jest Cheatsheet ## `spyOn` modules ```typescript= // myModule.ts export function foo () { return true } ``` ```typescript= // anotherModule.spec.ts import * as myModule from './myModule' const spyOnMyModule = jest.spyOn(myModule, 'foo') spyOnMyModule.mockReturnValue(true) ``` ## 模擬 HTMLElement 部分屬性 ```typescript const table = document.createElement('div'); const mockTableSetScrollTop = jest.fn() Object.defineProperty(table, 'scrollTop', { get: () => 500, set: mockTableSetScrollTop, }); ``` ## 檢查函式呼叫帶的參數是否部分匹配 ```typescript= 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()` 之間的執行順序 ```typescript= 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 的給覆蓋掉。 ## 測試元素的某個方法有無被呼叫 ```typescript= 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(); }); ``` ## 計算覆蓋率 ```sh jest --coverage ``` ```sh jest --coverage --collectCoverageFrom=<file-path> ``` ## 檔案變動時自動重跑測試 ```sh jest --watch ``` ```sh jest --watchAll ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up