Skip to content
Open
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { setTimeout } from 'node:timers/promises'

export function initTelemetry() {
return {
async record(event: string, data: Record<string, unknown>) {
async record(event: string, data: Record<string, unknown> | null) {
await setTimeout(6000)
},
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ I will also provide the _factory function_ to control the exact exports returned
```ts filename=authorize.test.ts nonumber lines=3,7
import { authorize, User } from './authorize.js'

const queryTableMock = vi.hoisted(() => vi.fn<() => Promise<User>>())
const queryTableMock = vi.hoisted(() => vi.fn<() => Promise<User | null>>())

vi.mock(import('@workshop/epic-sdk'), async () => {
return {
Expand All @@ -40,7 +40,7 @@ vi.mock(import('@workshop/epic-sdk'), async () => {
:owl: Since `vi.mock()` function is _hoisted_ (gets evaluated as the first thing no matter where it's defined), it won't be able to reference any values in the test's scope, like the `queryTableMock` function. To solve this, I wrap the mock function in the [`vi.hoisted()`](https://vitest.dev/api/vi.html#vi-hoisted) utility:

```ts filename=authorize.test.ts nonumber
const queryTableMock = vi.hoisted(() => vi.fn<() => Promise<User>>())
const queryTableMock = vi.hoisted(() => vi.fn<() => Promise<User | null>>())
```

This will expose the `queryTableMock` function to the `vi.mock()` factory correctly so it can use it as the value of the `queryTable` export. Nice!
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { authorize, User } from './authorize.js'

const queryTableMock = vi.hoisted(() => vi.fn<() => Promise<User>>())
const queryTableMock = vi.hoisted(() => vi.fn<() => Promise<User | null>>())

vi.mock(import('@workshop/epic-sdk'), async () => {
return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export async function authorize(userId: string) {
// As a part of authorization, we need to query the database
// for the given user. For that, we are using an imaginary
// third-party SDK package that performs SQL operations for us.
const user = await queryTable<User>('users', {
const user = await queryTable<User | null>('users', {
where: { id: { equals: userId } },
}).catch((error) => {
throw new Error(`Failed to fetch user by id "${userId}"`, {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"compilerOptions": {
"strict": true,
"module": "NodeNext",
"target": "ES2022",
"esModuleInterop": true,
Expand Down