Norman's Note 諾曼筆記

Norman's Note 諾曼筆記

Jest testing 測試

Change data-testid,不使用預設的 testid 作為抓取的標記

configure({testIdAttribute: 'not-data-testid'})

Snapshot Testing

Jest JS

  • Mock

window.scrollTo = jest.fn();


常用 Methods

describe('useFoo', () => {
  test('Bar', () => {
    const { result } = renderHook(() => useFoo());

    act(() => result.current.handleClick());

    // toEqual 用於比較 object

describe.each(table)(name, fn, timeout)

Use describe.each if you keep duplicating the same test suites with different data. describe.each allows you to write the test suite once and pass data in.

table: Array of Arrays with the arguments that are passed into the fn for each row.
name: String the title of the test suite.

fn: Function the suite of tests to be ran, this is the function that will receive the parameters in each row as function arguments.

  [1, 1, 2],
  [1, 2, 3],
  [2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
  test(`returns ${expected}`, () => {
    expect(a + b).toBe(expected);

  test(`returned value not be greater than ${expected}`, () => {
    expect(a + b).not.toBeGreaterThan(expected);

  test(`returned value not be less than ${expected}`, () => {
    expect(a + b).not.toBeLessThan(expected);


Jest CLI Options

jest (Watch Usage) 可用參數

› Press o to only run tests related to changed files. (不會全部跑)

› Press f to run only failed tests.
› Press p to filter by a filename regex pattern.
› Press t to filter by a test name regex pattern.
› Press q to quit watch mode.
› Press Enter to trigger a test run.


  1. Local: localhost
  2. DEV: 開發者用的機器
  3. SIT: 測試資料、只有內網可以連 (or VPN)
  4. UAT: production 資料、外網要先打帳號密碼才能連