Skip to content

Commit f4f175b

Browse files
committed
refactor: use snapshot serializer + snapshot error matcher instead of try/catch
1 parent 532e25b commit f4f175b

File tree

3 files changed

+24
-11
lines changed

3 files changed

+24
-11
lines changed

test/__snapshots__/extend.test.ts.snap

+3-3
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@
33
exports[`lib/extend.ts should handle the LabelText methods 1`] = `"<input id=\\"label-text-input\\" type=\\"text\\">"`;
44
55
exports[`lib/extend.ts should handle the get* method failures 1`] = `
6-
"TestingLibraryElementError: Unable to find an element with the title: missing.
6+
TestingLibraryElementError: Unable to find an element with the title: missing.
77
88
<div
9-
id=\\"scoped\\"
9+
id="scoped"
1010
>
1111
1212
@@ -16,7 +16,7 @@ exports[`lib/extend.ts should handle the get* method failures 1`] = `
1616
1717
1818
</div>
19-
<stack>:X:X"
19+
<stack>:X:X
2020
`;
2121
2222
exports[`lib/extend.ts should handle the get* methods 1`] = `"<input type=\\"text\\" data-testid=\\"testid-text-input\\">"`;

test/extend.test.ts

+5-8
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
import * as path from 'path'
22
import * as playwright from 'playwright'
33

4+
import stacktraceSerializer from './serializers/stacktrace'
5+
6+
expect.addSnapshotSerializer(stacktraceSerializer)
7+
48
describe('lib/extend.ts', () => {
59
let browser: playwright.ChromiumBrowser
610
let page: playwright.Page
@@ -52,14 +56,7 @@ describe('lib/extend.ts', () => {
5256
// Use the scoped element so the pretty HTML snapshot is smaller
5357
const scope = await document.$('#scoped')
5458

55-
try {
56-
await scope!.getByTitle('missing')
57-
fail() // eslint-disable-line jest/no-jasmine-globals
58-
} catch (err) {
59-
err.message = err.message.replace(/(\s*at .*(\n|$))+/gm, '\n <stack>:X:X')
60-
// eslint-disable-next-line jest/no-try-expect
61-
expect(err.message).toMatchSnapshot()
62-
}
59+
await expect(async () => scope!.getByTitle('missing')).rejects.toThrowErrorMatchingSnapshot()
6360
})
6461

6562
it('should handle the LabelText methods', async () => {

test/serializers/stacktrace.ts

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
type Serializer = Parameters<typeof expect.addSnapshotSerializer>['0']
2+
3+
const EXPRESSION = /(\s*at .*(\n|$))+/gm
4+
const PLACEHOLDER = '\n <stack>:X:X'
5+
6+
const serializer: Serializer = {
7+
serialize(val) {
8+
return typeof val === 'string' ? val.replace(EXPRESSION, PLACEHOLDER) : val
9+
},
10+
11+
test(val) {
12+
return typeof val === 'string' && EXPRESSION.test(val)
13+
},
14+
}
15+
16+
export default serializer

0 commit comments

Comments
 (0)