Skip to content

refactor: add type safety in utils.test.ts #4091

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 16, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 5 additions & 9 deletions site/src/components/GlobalSnackbar/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,27 +48,23 @@ describe("Snackbar", () => {

describe("displaySuccess", () => {
const originalWindowDispatchEvent = window.dispatchEvent
let dispatchEventMock: jest.Mock
type TDispatchEventMock = jest.MockedFunction<(msg: CustomEvent<NotificationMsg>) => boolean>
let dispatchEventMock: TDispatchEventMock

// Helper function to extract the notification event
// that was sent to `dispatchEvent`. This lets us validate
// the contents of the notification event are what we expect.
const extractNotificationEvent = (dispatchEventMock: jest.Mock): NotificationMsg => {
// The jest mock API isn't typesafe - but we know in our usage that
// this will always be a `NotificationMsg`.

const extractNotificationEvent = (dispatchEventMock: TDispatchEventMock): NotificationMsg => {
// calls[0] is the first call made to the mock (this is reset in `beforeEach`)
// calls[0][0] is the first argument of the first call
// calls[0][0].detail is the 'detail' argument passed to the `CustomEvent` -
// this is the `NotificationMsg` object that gets sent to `dispatchEvent`

// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
return dispatchEventMock.mock.calls[0][0].detail as NotificationMsg
return dispatchEventMock.mock.calls[0][0].detail
}

beforeEach(() => {
dispatchEventMock = jest.fn()
window.dispatchEvent = dispatchEventMock
window.dispatchEvent = dispatchEventMock as unknown as typeof window.dispatchEvent
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is the only way to properly type this:

  1. as unknown "Don't worry, I'm casting my thing unknown type before my assertion"
  2. as typeof window.dispatchEvent "This is what it actually is"

})

afterEach(() => {
Expand Down