File size: 11,990 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import type { MatcherContext } from 'expect'
import { toMatchInlineSnapshot } from 'jest-snapshot'
import {
  assertHasRedbox,
  getRedboxCallStack,
  getRedboxComponentStack,
  getRedboxDescription,
  getRedboxEnvironmentLabel,
  getRedboxSource,
  getRedboxLabel,
  getRedboxTotalErrorCount,
  openRedbox,
} from './next-test-utils'
import type { Playwright } from 'next-webdriver'
import { NextInstance } from 'e2e-utils'

declare global {
  namespace jest {
    // eslint-disable-next-line @typescript-eslint/no-unused-vars -- module augmentation needs to match generic params even if unused
    interface Matchers<R> {
      /**
       * Inline snapshot matcher for a Redbox that's popped up by default.
       * When a Redbox is hidden at first and requires manual display by clicking the toast,
       * use {@link toDisplayCollapsedRedbox} instead.
       *
       *
       * If the project root appears in the snapshot, pass in the `NextInstance`
       * as well to normalize the snapshot e.g. `await expect({ browser, next }).toDisplayRedbox()`.
       *
       * Unintented content in the snapshot should be reported to the Next.js DX team.
       * `<FIXME-internal-frame>` in the snapshot would be unintended.
       * `<FIXME-project-root>` in the snapshot would be unintended.
       * `<FIXME-file-protocol>` in the snapshot would be unintended.
       * `<FIXME-next-dist-dir>` in the snapshot would be unintended.
       * Any node_modules in the snapshot would be unintended.
       * Differences in the snapshot between Turbopack and Webpack would be unintended.
       *
       * @param inlineSnapshot - The snapshot to compare against.
       */
      toDisplayRedbox(
        inlineSnapshot?: string,
        opts?: ErrorSnapshotOptions
      ): Promise<void>

      /**
       * Inline snapshot matcher for a Redbox that's collapsed by default.
       * When a Redbox is immediately displayed,
       * use {@link toDisplayRedbox} instead.
       *
       * If the project root appears in the snapshot, pass in the `NextInstance`
       * as well to normalize the snapshot e.g. `await expect({ browser, next }).toDisplayCollapsedRedbox()`.
       *
       * Unintented content in the snapshot should be reported to the Next.js DX team.
       * `<FIXME-internal-frame>` in the snapshot would be unintended.
       * `<FIXME-project-root>` in the snapshot would be unintended.
       * `<FIXME-file-protocol>` in the snapshot would be unintended.
       * `<FIXME-next-dist-dir>` in the snapshot would be unintended.
       * Any node_modules in the snapshot would be unintended.
       * Differences in the snapshot between Turbopack and Webpack would be unintended.
       *
       * @param inlineSnapshot - The snapshot to compare against.
       */
      toDisplayCollapsedRedbox(
        inlineSnapshot?: string,
        opts?: ErrorSnapshotOptions
      ): Promise<void>
    }
  }
}

interface ErrorSnapshotOptions {
  label?: boolean
}

interface ErrorSnapshot {
  environmentLabel: string | null
  label: string | null
  description: string | null
  componentStack?: string
  source: string | null
  stack: string[] | null
}

async function createErrorSnapshot(
  browser: Playwright,
  next: NextInstance | null,
  { label: includeLabel = true }: ErrorSnapshotOptions = {}
): Promise<ErrorSnapshot> {
  const [label, environmentLabel, description, source, stack, componentStack] =
    await Promise.all([
      includeLabel ? getRedboxLabel(browser) : null,
      getRedboxEnvironmentLabel(browser),
      getRedboxDescription(browser),
      getRedboxSource(browser),
      getRedboxCallStack(browser),
      getRedboxComponentStack(browser),
    ])

  // We don't need to test the codeframe logic everywhere.
  // Here we focus on the cursor position of the top most frame
  // From
  //
  // pages/index.js (3:11) @ eval
  //
  //   1 | export default function Page() {
  //   2 |   [1, 2, 3].map(() => {
  // > 3 |     throw new Error("anonymous error!");
  //     |           ^
  //   4 |   })
  //   5 | }
  //
  // to
  //
  // pages/index.js (3:11) @ Page
  // > 3 |     throw new Error("anonymous error!");
  //     |           ^
  let focusedSource = source
  if (source !== null) {
    focusedSource = ''
    const sourceFrameLines = source.split('\n')
    for (let i = 0; i < sourceFrameLines.length; i++) {
      const sourceFrameLine = sourceFrameLines[i].trimEnd()
      if (sourceFrameLine === '') {
        continue
      }

      if (sourceFrameLine.startsWith('>')) {
        // This is where the cursor will point
        // Include the cursor and nothing below since it's just surrounding code.
        focusedSource += '\n' + sourceFrameLine
        focusedSource += '\n' + sourceFrameLines[i + 1]
        break
      }
      const isCodeFrameLine = /^ {2}\s*\d+ \|/.test(sourceFrameLine)
      if (!isCodeFrameLine) {
        focusedSource += '\n' + sourceFrameLine
      }
    }

    focusedSource = focusedSource.trim()

    if (next !== null) {
      focusedSource = focusedSource.replaceAll(
        next.testDir,
        '<FIXME-project-root>'
      )
    }

    // This is the processed path the nextjs file from node_modules,
    // likely not being processed properly and it's not deterministic among tests.
    // e.g. it could be a encoded url of loader path:
    // ../packages/next/dist/build/webpack/loaders/next-app-loader/index.js...
    const sourceLines = focusedSource.split('\n')
    if (
      sourceLines[0].startsWith('./node_modules/.pnpm/next@file+') ||
      sourceLines[0].startsWith('./node_modules/.pnpm/file+') ||
      // e.g. "next-app-loader?<SEARCH PARAMS>" (in rspack, the loader doesn't seem to be prefixed with node_modules)
      /^next-[a-zA-Z0-9\-_]+?-loader\?/.test(sourceLines[0])
    ) {
      focusedSource =
        `<FIXME-nextjs-internal-source>` +
        '\n' +
        sourceLines.slice(1).join('\n')
    }
  }

  let sanitizedDescription = description

  if (sanitizedDescription) {
    sanitizedDescription = sanitizedDescription
      .replace(/{imported module [^}]+}/, '<turbopack-module-id>')
      .replace(/\w+_WEBPACK_IMPORTED_MODULE_\w+/, '<webpack-module-id>')

    if (next !== null) {
      sanitizedDescription = sanitizedDescription.replace(
        next.testDir,
        '<FIXME-project-root>'
      )
    }
  }

  const snapshot: ErrorSnapshot = {
    environmentLabel,
    label: label ?? '<FIXME-excluded-label>',
    description: sanitizedDescription,
    source: focusedSource,
    stack:
      next !== null && stack !== null
        ? stack.map((stackframe) => {
            return stackframe.replace(next.testDir, '<FIXME-project-root>')
          })
        : stack,
  }

  // Hydration diffs are only relevant to some specific errors
  // so we hide them from the snapshots unless they are present.
  if (componentStack !== null) {
    snapshot.componentStack = componentStack
  }

  return snapshot
}

type RedboxSnapshot = ErrorSnapshot | ErrorSnapshot[]

async function createRedboxSnapshot(
  browser: Playwright,
  next: NextInstance | null,
  opts?: ErrorSnapshotOptions
): Promise<RedboxSnapshot> {
  const errorTally = await getRedboxTotalErrorCount(browser)
  const errorSnapshots: ErrorSnapshot[] = []

  for (let errorIndex = 0; errorIndex < errorTally; errorIndex++) {
    const errorSnapshot = await createErrorSnapshot(browser, next, opts)
    errorSnapshots.push(errorSnapshot)

    if (errorIndex < errorTally - 1) {
      // Go to next error
      await browser
        .waitForElementByCss('[data-nextjs-dialog-error-next]')
        .click()
      // TODO: Wait for suspended content if the click triggered it.
      await browser.waitForElementByCss(
        `[data-nextjs-dialog-error-index="${errorIndex + 1}"]`
      )
    }
  }

  return errorSnapshots.length === 1
    ? // Most of the Redbox tests will just show a single error.
      // We optimize display for that case.
      errorSnapshots[0]
    : errorSnapshots
}

expect.extend({
  async toDisplayRedbox(
    this: MatcherContext,
    browserOrContext: Playwright | { browser: Playwright; next: NextInstance },
    expectedRedboxSnapshot?: string,
    opts?: ErrorSnapshotOptions
  ) {
    let browser: Playwright
    let next: NextInstance | null
    if ('browser' in browserOrContext && 'next' in browserOrContext) {
      browser = browserOrContext.browser
      next = browserOrContext.next
    } else {
      browser = browserOrContext
      next = null
    }

    // Otherwise jest uses the async stack trace which makes it impossible to know the actual callsite of `toMatchSpeechInlineSnapshot`.
    // @ts-expect-error -- Not readonly
    this.error = new Error()
    // Abort test on first mismatch.
    // Subsequent actions will be based on an incorrect state otherwise and almost always fail as well.
    // TODO: Actually, we may want to proceed. Kinda nice to also do more assertions later.
    this.dontThrow = () => {}

    try {
      await assertHasRedbox(browser)
    } catch (cause) {
      // argument length is relevant.
      // Jest will update absent snapshots but fail if you specify a snapshot even if undefined.
      if (expectedRedboxSnapshot === undefined) {
        return toMatchInlineSnapshot.call(this, String(cause.message))
      } else {
        return toMatchInlineSnapshot.call(
          this,
          String(cause.message),
          expectedRedboxSnapshot
        )
      }
    }

    const redbox = await createRedboxSnapshot(browser, next, opts)

    // argument length is relevant.
    // Jest will update absent snapshots but fail if you specify a snapshot even if undefined.
    if (expectedRedboxSnapshot === undefined) {
      return toMatchInlineSnapshot.call(this, redbox)
    } else {
      return toMatchInlineSnapshot.call(this, redbox, expectedRedboxSnapshot)
    }
  },
  async toDisplayCollapsedRedbox(
    this: MatcherContext,
    browserOrContext: Playwright | { browser: Playwright; next: NextInstance },
    expectedRedboxSnapshot?: string,
    opts?: ErrorSnapshotOptions
  ) {
    let browser: Playwright
    let next: NextInstance | null
    if ('browser' in browserOrContext && 'next' in browserOrContext) {
      browser = browserOrContext.browser
      next = browserOrContext.next
    } else {
      browser = browserOrContext
      next = null
    }

    // Otherwise jest uses the async stack trace which makes it impossible to know the actual callsite of `toMatchSpeechInlineSnapshot`.
    // @ts-expect-error -- Not readonly
    this.error = new Error()
    // Abort test on first mismatch.
    // Subsequent actions will be based on an incorrect state otherwise and almost always fail as well.
    // TODO: Actually, we may want to proceed. Kinda nice to also do more assertions later.
    this.dontThrow = () => {}

    try {
      await openRedbox(browser)
    } catch (cause) {
      // argument length is relevant.
      // Jest will update absent snapshots but fail if you specify a snapshot even if undefined.
      if (expectedRedboxSnapshot === undefined) {
        return toMatchInlineSnapshot.call(
          this,
          String(cause.message)
            // Should switch to `toDisplayRedbox` not `assertHasRedbox`
            .replace('assertHasRedbox', 'toDisplayRedbox')
        )
      } else {
        return toMatchInlineSnapshot.call(
          this,
          String(cause.message)
            // Should switch to `toDisplayRedbox` not `assertHasRedbox`
            .replace('assertHasRedbox', 'toDisplayRedbox'),
          expectedRedboxSnapshot
        )
      }
    }

    const redbox = await createRedboxSnapshot(browser, next, opts)

    // argument length is relevant.
    // Jest will update absent snapshots but fail if you specify a snapshot even if undefined.
    if (expectedRedboxSnapshot === undefined) {
      return toMatchInlineSnapshot.call(this, redbox)
    } else {
      return toMatchInlineSnapshot.call(this, redbox, expectedRedboxSnapshot)
    }
  },
})