Skip to content

Latest commit

 

History

History
90 lines (68 loc) · 2.63 KB

testing.md

File metadata and controls

90 lines (68 loc) · 2.63 KB

Testing

Bug fixes and features should always come with tests.

Testing Tools

  • Unit - test both frontend code in isolation
  • Workflows - tools and libraries for GitHub Workflows or any DevOps processes
    • act - Emulates GitHub Workflows virtual environment via Docker containers.

Testing UI Business Logic

Separate the business logic from the view as much as possible. Create hooks, helpers & reducers to utilize this logic from the UI and test that code in isolation from its UI.

Unit Testing

This is an example of how we structure our unit tests.

import mockAxios from 'axios'
import { isLoggedIn } from './isLoggedIn'
import { describe, it, expect } from 'vitest'

const UserData = { id: 1, name: 'UserName' }

const mockUserData = id => {
  mockAxios.get.mockImplementationOnce(() => Promise.resolve(id ? Userdata : undefined))
}

describe('isLoggedIn', () => {
  describe('isLoggedIn', () => {
    it('should return true when passed a userId', () => {
      const userId = 1
      mockUserData(userId)
      expect(isLoggedIn(userId)).toBe(true)
    })

    it('should return false when userId is undefined', () => {
      const userId = undefined
      mockUserData(userId)
      expect(isLoggedIn(userId)).toBe(false)
    })
  })
})

Hook Testing

This is an example of how we structure our hook tests.

import { renderHook } from '@testing-library/react'
import { useIsComponentMounted } from './useIsComponentMounted'

const setup = () => {
  return renderHook(() => useIsComponentMounted())
}
describe('useIsComponentMounted hook', () => {
  it('should be true on render', () => {
    const { result } = setup()
    expect(result.current.current).toBe(true)
  })

  it('should be false on unmount', () => {
    const { result, unmount } = setup()
    unmount()
    expect(result.current.current).toBe(false)
  })
})

Workflow Testing

Requirements:

Example command to test Cypress GitHub action:

# run from project root
act -s GITHUB_TOKEN=$GITHUB_TOKEN -j test-chrome --reuse

NOTE: there are two parameters set in the project's root .actrc file.

Two important flags that can be passed to the act command:

  • --reuse - persist state across runs
  • --rm - remove container on failure