/
matchers.ts
362 lines (331 loc) · 14.7 KB
/
matchers.ts
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
/**
* Copyright Microsoft Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type { Locator, Page, APIResponse } from 'playwright-core';
import type { FrameExpectOptions } from 'playwright-core/lib/client/types';
import { colors } from 'playwright-core/lib/utilsBundle';
import { constructURLBasedOnBaseURL } from 'playwright-core/lib/utils';
import type { Expect } from '../types';
import { expectTypes, callLogText } from '../util';
import { toBeTruthy } from './toBeTruthy';
import { toEqual } from './toEqual';
import { toExpectedTextValues, toMatchText } from './toMatchText';
import type { ParsedStackTrace } from 'playwright-core/lib/utils/stackTrace';
import { isTextualMimeType } from 'playwright-core/lib/utils/mimeType';
import { monotonicTime } from 'playwright-core/lib/utils';
import { raceAgainstTimeout } from 'playwright-core/lib/utils/timeoutRunner';
interface LocatorEx extends Locator {
_expect(customStackTrace: ParsedStackTrace, expression: string, options: Omit<FrameExpectOptions, 'expectedValue'> & { expectedValue?: any }): Promise<{ matches: boolean, received?: any, log?: string[], timedOut?: boolean }>;
}
interface APIResponseEx extends APIResponse {
_fetchLog(): Promise<string[]>;
}
export function toBeChecked(
this: ReturnType<Expect['getState']>,
locator: LocatorEx,
options?: { checked?: boolean, timeout?: number },
) {
return toBeTruthy.call(this, 'toBeChecked', locator, 'Locator', async (isNot, timeout, customStackTrace) => {
const checked = !options || options.checked === undefined || options.checked === true;
return await locator._expect(customStackTrace, checked ? 'to.be.checked' : 'to.be.unchecked', { isNot, timeout });
}, options);
}
export function toBeDisabled(
this: ReturnType<Expect['getState']>,
locator: LocatorEx,
options?: { timeout?: number },
) {
return toBeTruthy.call(this, 'toBeDisabled', locator, 'Locator', async (isNot, timeout, customStackTrace) => {
return await locator._expect(customStackTrace, 'to.be.disabled', { isNot, timeout });
}, options);
}
export function toBeEditable(
this: ReturnType<Expect['getState']>,
locator: LocatorEx,
options?: { editable?: boolean, timeout?: number },
) {
return toBeTruthy.call(this, 'toBeEditable', locator, 'Locator', async (isNot, timeout, customStackTrace) => {
const editable = !options || options.editable === undefined || options.editable === true;
return await locator._expect(customStackTrace, editable ? 'to.be.editable' : 'to.be.readonly', { isNot, timeout });
}, options);
}
export function toBeEmpty(
this: ReturnType<Expect['getState']>,
locator: LocatorEx,
options?: { timeout?: number },
) {
return toBeTruthy.call(this, 'toBeEmpty', locator, 'Locator', async (isNot, timeout, customStackTrace) => {
return await locator._expect(customStackTrace, 'to.be.empty', { isNot, timeout });
}, options);
}
export function toBeEnabled(
this: ReturnType<Expect['getState']>,
locator: LocatorEx,
options?: { enabled?: boolean, timeout?: number },
) {
return toBeTruthy.call(this, 'toBeEnabled', locator, 'Locator', async (isNot, timeout, customStackTrace) => {
const enabled = !options || options.enabled === undefined || options.enabled === true;
return await locator._expect(customStackTrace, enabled ? 'to.be.enabled' : 'to.be.disabled', { isNot, timeout });
}, options);
}
export function toBeFocused(
this: ReturnType<Expect['getState']>,
locator: LocatorEx,
options?: { timeout?: number },
) {
return toBeTruthy.call(this, 'toBeFocused', locator, 'Locator', async (isNot, timeout, customStackTrace) => {
return await locator._expect(customStackTrace, 'to.be.focused', { isNot, timeout });
}, options);
}
export function toBeHidden(
this: ReturnType<Expect['getState']>,
locator: LocatorEx,
options?: { timeout?: number },
) {
return toBeTruthy.call(this, 'toBeHidden', locator, 'Locator', async (isNot, timeout, customStackTrace) => {
return await locator._expect(customStackTrace, 'to.be.hidden', { isNot, timeout });
}, options);
}
export function toBeVisible(
this: ReturnType<Expect['getState']>,
locator: LocatorEx,
options?: { visible?: boolean, timeout?: number },
) {
return toBeTruthy.call(this, 'toBeVisible', locator, 'Locator', async (isNot, timeout, customStackTrace) => {
const visible = !options || options.visible === undefined || options.visible === true;
return await locator._expect(customStackTrace, visible ? 'to.be.visible' : 'to.be.hidden', { isNot, timeout });
}, options);
}
export function toContainText(
this: ReturnType<Expect['getState']>,
locator: LocatorEx,
expected: string | RegExp | (string | RegExp)[],
options: { timeout?: number, useInnerText?: boolean, ignoreCase?: boolean } = {},
) {
if (Array.isArray(expected)) {
return toEqual.call(this, 'toContainText', locator, 'Locator', async (isNot, timeout, customStackTrace) => {
const expectedText = toExpectedTextValues(expected, { matchSubstring: true, normalizeWhiteSpace: true, ignoreCase: options.ignoreCase });
return await locator._expect(customStackTrace, 'to.contain.text.array', { expectedText, isNot, useInnerText: options.useInnerText, timeout });
}, expected, { ...options, contains: true });
} else {
return toMatchText.call(this, 'toContainText', locator, 'Locator', async (isNot, timeout, customStackTrace) => {
const expectedText = toExpectedTextValues([expected], { matchSubstring: true, normalizeWhiteSpace: true, ignoreCase: options.ignoreCase });
return await locator._expect(customStackTrace, 'to.have.text', { expectedText, isNot, useInnerText: options.useInnerText, timeout });
}, expected, options);
}
}
export function toHaveAttribute(
this: ReturnType<Expect['getState']>,
locator: LocatorEx,
name: string,
expected: string | RegExp,
options?: { timeout?: number },
) {
return toMatchText.call(this, 'toHaveAttribute', locator, 'Locator', async (isNot, timeout, customStackTrace) => {
const expectedText = toExpectedTextValues([expected]);
return await locator._expect(customStackTrace, 'to.have.attribute', { expressionArg: name, expectedText, isNot, timeout });
}, expected, options);
}
export function toHaveClass(
this: ReturnType<Expect['getState']>,
locator: LocatorEx,
expected: string | RegExp | (string | RegExp)[],
options?: { timeout?: number },
) {
if (Array.isArray(expected)) {
return toEqual.call(this, 'toHaveClass', locator, 'Locator', async (isNot, timeout, customStackTrace) => {
const expectedText = toExpectedTextValues(expected);
return await locator._expect(customStackTrace, 'to.have.class.array', { expectedText, isNot, timeout });
}, expected, options);
} else {
return toMatchText.call(this, 'toHaveClass', locator, 'Locator', async (isNot, timeout, customStackTrace) => {
const expectedText = toExpectedTextValues([expected]);
return await locator._expect(customStackTrace, 'to.have.class', { expectedText, isNot, timeout });
}, expected, options);
}
}
export function toHaveCount(
this: ReturnType<Expect['getState']>,
locator: LocatorEx,
expected: number,
options?: { timeout?: number },
) {
return toEqual.call(this, 'toHaveCount', locator, 'Locator', async (isNot, timeout, customStackTrace) => {
return await locator._expect(customStackTrace, 'to.have.count', { expectedNumber: expected, isNot, timeout });
}, expected, options);
}
export function toHaveCSS(
this: ReturnType<Expect['getState']>,
locator: LocatorEx,
name: string,
expected: string | RegExp,
options?: { timeout?: number },
) {
return toMatchText.call(this, 'toHaveCSS', locator, 'Locator', async (isNot, timeout, customStackTrace) => {
const expectedText = toExpectedTextValues([expected]);
return await locator._expect(customStackTrace, 'to.have.css', { expressionArg: name, expectedText, isNot, timeout });
}, expected, options);
}
export function toHaveId(
this: ReturnType<Expect['getState']>,
locator: LocatorEx,
expected: string | RegExp,
options?: { timeout?: number },
) {
return toMatchText.call(this, 'toHaveId', locator, 'Locator', async (isNot, timeout, customStackTrace) => {
const expectedText = toExpectedTextValues([expected]);
return await locator._expect(customStackTrace, 'to.have.id', { expectedText, isNot, timeout });
}, expected, options);
}
export function toHaveJSProperty(
this: ReturnType<Expect['getState']>,
locator: LocatorEx,
name: string,
expected: any,
options?: { timeout?: number },
) {
return toEqual.call(this, 'toHaveJSProperty', locator, 'Locator', async (isNot, timeout, customStackTrace) => {
return await locator._expect(customStackTrace, 'to.have.property', { expressionArg: name, expectedValue: expected, isNot, timeout });
}, expected, options);
}
export function toHaveText(
this: ReturnType<Expect['getState']>,
locator: LocatorEx,
expected: string | RegExp | (string | RegExp)[],
options: { timeout?: number, useInnerText?: boolean, ignoreCase?: boolean } = {},
) {
if (Array.isArray(expected)) {
return toEqual.call(this, 'toHaveText', locator, 'Locator', async (isNot, timeout, customStackTrace) => {
const expectedText = toExpectedTextValues(expected, { normalizeWhiteSpace: true, ignoreCase: options.ignoreCase });
return await locator._expect(customStackTrace, 'to.have.text.array', { expectedText, isNot, useInnerText: options?.useInnerText, timeout });
}, expected, options);
} else {
return toMatchText.call(this, 'toHaveText', locator, 'Locator', async (isNot, timeout, customStackTrace) => {
const expectedText = toExpectedTextValues([expected], { normalizeWhiteSpace: true, ignoreCase: options.ignoreCase });
return await locator._expect(customStackTrace, 'to.have.text', { expectedText, isNot, useInnerText: options?.useInnerText, timeout });
}, expected, options);
}
}
export function toHaveValue(
this: ReturnType<Expect['getState']>,
locator: LocatorEx,
expected: string | RegExp,
options?: { timeout?: number },
) {
return toMatchText.call(this, 'toHaveValue', locator, 'Locator', async (isNot, timeout, customStackTrace) => {
const expectedText = toExpectedTextValues([expected]);
return await locator._expect(customStackTrace, 'to.have.value', { expectedText, isNot, timeout });
}, expected, options);
}
export function toHaveValues(
this: ReturnType<Expect['getState']>,
locator: LocatorEx,
expected: (string | RegExp)[],
options?: { timeout?: number },
) {
return toEqual.call(this, 'toHaveValues', locator, 'Locator', async (isNot, timeout, customStackTrace) => {
const expectedText = toExpectedTextValues(expected);
return await locator._expect(customStackTrace, 'to.have.values', { expectedText, isNot, timeout });
}, expected, options);
}
export function toHaveTitle(
this: ReturnType<Expect['getState']>,
page: Page,
expected: string | RegExp,
options: { timeout?: number } = {},
) {
const locator = page.locator(':root') as LocatorEx;
return toMatchText.call(this, 'toHaveTitle', locator, 'Locator', async (isNot, timeout, customStackTrace) => {
const expectedText = toExpectedTextValues([expected], { normalizeWhiteSpace: true });
return await locator._expect(customStackTrace, 'to.have.title', { expectedText, isNot, timeout });
}, expected, options);
}
export function toHaveURL(
this: ReturnType<Expect['getState']>,
page: Page,
expected: string | RegExp,
options?: { timeout?: number },
) {
const baseURL = (page.context() as any)._options.baseURL;
expected = typeof expected === 'string' ? constructURLBasedOnBaseURL(baseURL, expected) : expected;
const locator = page.locator(':root') as LocatorEx;
return toMatchText.call(this, 'toHaveURL', locator, 'Locator', async (isNot, timeout, customStackTrace) => {
const expectedText = toExpectedTextValues([expected]);
return await locator._expect(customStackTrace, 'to.have.url', { expectedText, isNot, timeout });
}, expected, options);
}
export async function toBeOK(
this: ReturnType<Expect['getState']>,
response: APIResponseEx
) {
const matcherName = 'toBeOK';
expectTypes(response, ['APIResponse'], matcherName);
const contentType = response.headers()['content-type'];
const isTextEncoding = contentType && isTextualMimeType(contentType);
const [log, text] = (this.isNot === response.ok()) ? await Promise.all([
response._fetchLog(),
isTextEncoding ? response.text() : null
]) : [];
const message = () => this.utils.matcherHint(matcherName, undefined, '', { isNot: this.isNot }) +
callLogText(log) +
(text === null ? '' : `\nResponse text:\n${colors.dim(text?.substring(0, 1000) || '')}`);
const pass = response.ok();
return { message, pass };
}
export async function toPass(
this: ReturnType<Expect['getState']>,
callback: () => void,
options: {
intervals?: number[];
timeout?: number,
} = {},
) {
let matcherError: Error | undefined;
const startTime = monotonicTime();
const pollIntervals = options.intervals || [100, 250, 500, 1000];
const lastPollInterval = pollIntervals[pollIntervals.length - 1] || 1000;
const timeout = options.timeout !== undefined ? options.timeout : 0;
const isNot = this.isNot;
while (true) {
const elapsed = monotonicTime() - startTime;
if (timeout !== 0 && elapsed > timeout)
break;
try {
const wrappedCallback = () => Promise.resolve().then(callback);
const received = timeout !== 0 ? await raceAgainstTimeout(wrappedCallback, timeout - elapsed)
: await wrappedCallback().then(() => ({ timedOut: false }));
if (received.timedOut)
break;
// The check passed, exit sucessfully.
if (isNot)
matcherError = new Error('Expected to fail, but passed');
else
return { message: () => '', pass: true };
} catch (e) {
if (isNot)
return { message: () => '', pass: false };
matcherError = e;
}
await new Promise(x => setTimeout(x, pollIntervals!.shift() ?? lastPollInterval));
}
const timeoutMessage = `Timeout ${timeout}ms exceeded while waiting on the predicate`;
const message = () => matcherError ? [
matcherError.message,
'',
`Call Log:`,
`- ${timeoutMessage}`,
].join('\n') : timeoutMessage;
return { message, pass: isNot ? true : false };
}