Wiki

Testing

Gotchas

When testing an event on a button that is managed with react-aria useButton, you have to fire the event on a child of the button, otherwise that event handlers on the button may not trigger correctly.

// component jsx
const { buttonProps } = useButton()
<button title="Click me" {...buttonProps}>Click me</button>

// test
const user = userEvent.setup()
user.click(screen.getByTitle('Click me')) // this doesn't trigger
user.click(screen.getByText('Click me')) // this does

Testing Strategies

Testing components that interact with remix

See

  • actionData.test.tsx example in this repo
  • https://remix.run/docs/en/main/utils/create-remix-stub
  • https://remix.run/docs/en/main/other-api/testing
  • https://testing.epicweb.dev/07

Testing a module that imports a json file

We want to test a function that uses an import statement to read a json file. Vitest allows us to mock the imported file, but this requires careful coordination of mocking methods and calls to the module under test. Here is how to do it:

// my-module.test.ts
import { vi } from 'vitest'

describe('Module that recommends a party location', () => {
  beforeEach(() => {
    vi.resetModules()
  })

  test('party outside when its warm', () => {
    vi.doMock("./temperature.json", async () => ({
        // this is where we mock the data that is imported
        default: { temperature: 30 }
    })
    const moduleUnderTest = await import('./party-location')
    expect(moduleUnderTest.shouldPartyOutside()).toEqual(true)
  })

  test('do not party outside when its cold', () => {
    vi.doMock("./some-data.json", async () => ({
        // this is where we mock the data that is imported
        default: { temperature: 12 }
    })
    const moduleUnderTest = await import('./party-location')
    expect(moduleUnderTest.shouldPartyOutside()).toEqual(false)
  })
})

// party-location.ts
import data from './temperature.json'

export function getData() {
    return data.temperature >= 20
}

We could import the module under test at the top of the file if we only mocked data once. However, we want to test multiple behaviours of our function based on different data. To do this, we re-import the file inside each test. resetModules makes sure that the module is not cached.