2021-06-06 17:09:53 -07:00
|
|
|
/**
|
|
|
|
* 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 expectLibrary from 'expect';
|
2022-03-18 17:31:26 -06:00
|
|
|
import { raceAgainstTimeout } from 'playwright-core/lib/utils/async';
|
2021-10-18 20:06:18 -08:00
|
|
|
import path from 'path';
|
2021-10-08 08:01:31 -07:00
|
|
|
import {
|
|
|
|
INVERTED_COLOR,
|
|
|
|
RECEIVED_COLOR,
|
|
|
|
printReceived,
|
|
|
|
} from 'jest-matcher-utils';
|
2021-07-28 15:44:44 -07:00
|
|
|
import {
|
|
|
|
toBeChecked,
|
|
|
|
toBeDisabled,
|
|
|
|
toBeEditable,
|
|
|
|
toBeEmpty,
|
|
|
|
toBeEnabled,
|
|
|
|
toBeFocused,
|
|
|
|
toBeHidden,
|
2021-11-30 18:12:19 -08:00
|
|
|
toBeOK,
|
2021-07-28 22:30:37 -07:00
|
|
|
toBeVisible,
|
2021-07-28 15:44:44 -07:00
|
|
|
toContainText,
|
2021-08-06 16:58:42 -07:00
|
|
|
toHaveAttribute,
|
2021-07-28 15:44:44 -07:00
|
|
|
toHaveClass,
|
2021-07-29 07:33:19 -07:00
|
|
|
toHaveCount,
|
2021-07-28 22:30:37 -07:00
|
|
|
toHaveCSS,
|
2021-07-28 15:44:44 -07:00
|
|
|
toHaveId,
|
2021-08-06 16:58:42 -07:00
|
|
|
toHaveJSProperty,
|
2021-07-28 15:44:44 -07:00
|
|
|
toHaveText,
|
2021-07-29 07:33:19 -07:00
|
|
|
toHaveTitle,
|
|
|
|
toHaveURL,
|
2021-07-28 15:44:44 -07:00
|
|
|
toHaveValue
|
2021-07-28 22:30:37 -07:00
|
|
|
} from './matchers/matchers';
|
2022-03-30 20:52:00 -08:00
|
|
|
import { toMatchSnapshot, toHaveScreenshot } from './matchers/toMatchSnapshot';
|
2021-08-02 22:11:37 -07:00
|
|
|
import type { Expect, TestError } from './types';
|
2021-07-30 16:07:02 -07:00
|
|
|
import matchers from 'expect/build/matchers';
|
|
|
|
import { currentTestInfo } from './globals';
|
2022-03-18 17:31:26 -06:00
|
|
|
import { serializeError, captureStackTrace, currentExpectTimeout } from './util';
|
|
|
|
import { monotonicTime } from 'playwright-core/lib/utils/utils';
|
2021-06-06 17:09:53 -07:00
|
|
|
|
2022-03-30 20:52:00 -08:00
|
|
|
// from expect/build/types
|
|
|
|
export type SyncExpectationResult = {
|
|
|
|
pass: boolean;
|
|
|
|
message: () => string;
|
|
|
|
};
|
|
|
|
|
2021-10-08 08:01:31 -07:00
|
|
|
// #region
|
|
|
|
// Mirrored from https://github.com/facebook/jest/blob/f13abff8df9a0e1148baf3584bcde6d1b479edc7/packages/expect/src/print.ts
|
|
|
|
/**
|
|
|
|
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
|
|
|
*
|
|
|
|
* This source code is licensed under the MIT license found here
|
|
|
|
* https://github.com/facebook/jest/blob/1547740bbc26400d69f4576bf35645163e942829/LICENSE
|
|
|
|
*/
|
|
|
|
|
|
|
|
// Format substring but do not enclose in double quote marks.
|
|
|
|
// The replacement is compatible with pretty-format package.
|
|
|
|
const printSubstring = (val: string): string => val.replace(/"|\\/g, '\\$&');
|
|
|
|
|
|
|
|
export const printReceivedStringContainExpectedSubstring = (
|
|
|
|
received: string,
|
|
|
|
start: number,
|
|
|
|
length: number, // not end
|
|
|
|
): string =>
|
|
|
|
RECEIVED_COLOR(
|
|
|
|
'"' +
|
|
|
|
printSubstring(received.slice(0, start)) +
|
|
|
|
INVERTED_COLOR(printSubstring(received.slice(start, start + length))) +
|
|
|
|
printSubstring(received.slice(start + length)) +
|
|
|
|
'"',
|
|
|
|
);
|
|
|
|
|
|
|
|
export const printReceivedStringContainExpectedResult = (
|
|
|
|
received: string,
|
|
|
|
result: RegExpExecArray | null,
|
|
|
|
): string =>
|
|
|
|
result === null
|
|
|
|
? printReceived(received)
|
|
|
|
: printReceivedStringContainExpectedSubstring(
|
|
|
|
received,
|
|
|
|
result.index,
|
|
|
|
result[0].length,
|
|
|
|
);
|
|
|
|
|
|
|
|
// #endregion
|
|
|
|
|
2022-03-18 17:31:26 -06:00
|
|
|
type ExpectMessageOrOptions = undefined | string | { message?: string, timeout?: number };
|
|
|
|
|
|
|
|
function createExpect(actual: unknown, messageOrOptions: ExpectMessageOrOptions, isSoft: boolean, isPoll: boolean) {
|
|
|
|
return new Proxy(expectLibrary(actual), new ExpectMetaInfoProxyHandler(messageOrOptions, isSoft, isPoll));
|
2022-02-02 19:33:51 -07:00
|
|
|
}
|
|
|
|
|
2022-01-31 18:14:59 -07:00
|
|
|
export const expect: Expect = new Proxy(expectLibrary as any, {
|
2022-03-18 17:31:26 -06:00
|
|
|
apply: function(target: any, thisArg: any, argumentsList: [actual: unknown, messageOrOptions: ExpectMessageOrOptions]) {
|
|
|
|
const [actual, messageOrOptions] = argumentsList;
|
|
|
|
return createExpect(actual, messageOrOptions, false /* isSoft */, false /* isPoll */);
|
2022-01-31 18:14:59 -07:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2022-03-18 17:31:26 -06:00
|
|
|
expect.soft = (actual: unknown, messageOrOptions: ExpectMessageOrOptions) => {
|
|
|
|
return createExpect(actual, messageOrOptions, true /* isSoft */, false /* isPoll */);
|
|
|
|
};
|
|
|
|
|
|
|
|
expect.poll = (actual: unknown, messageOrOptions: ExpectMessageOrOptions) => {
|
|
|
|
return createExpect(actual, messageOrOptions, false /* isSoft */, true /* isPoll */);
|
2022-02-02 19:33:51 -07:00
|
|
|
};
|
|
|
|
|
2021-07-27 20:26:12 -07:00
|
|
|
expectLibrary.setState({ expand: false });
|
2021-07-30 16:07:02 -07:00
|
|
|
const customMatchers = {
|
2021-07-28 12:07:11 -07:00
|
|
|
toBeChecked,
|
|
|
|
toBeDisabled,
|
|
|
|
toBeEditable,
|
|
|
|
toBeEmpty,
|
|
|
|
toBeEnabled,
|
|
|
|
toBeFocused,
|
|
|
|
toBeHidden,
|
2021-11-30 18:12:19 -08:00
|
|
|
toBeOK,
|
2021-07-28 12:07:11 -07:00
|
|
|
toBeVisible,
|
|
|
|
toContainText,
|
2021-08-06 16:58:42 -07:00
|
|
|
toHaveAttribute,
|
2021-07-28 15:44:44 -07:00
|
|
|
toHaveClass,
|
2021-07-29 07:33:19 -07:00
|
|
|
toHaveCount,
|
2021-07-28 22:30:37 -07:00
|
|
|
toHaveCSS,
|
2021-07-28 12:07:11 -07:00
|
|
|
toHaveId,
|
2021-08-06 16:58:42 -07:00
|
|
|
toHaveJSProperty,
|
2021-07-28 12:07:11 -07:00
|
|
|
toHaveText,
|
2021-07-29 07:33:19 -07:00
|
|
|
toHaveTitle,
|
|
|
|
toHaveURL,
|
2021-07-28 12:07:11 -07:00
|
|
|
toHaveValue,
|
|
|
|
toMatchSnapshot,
|
2022-02-28 13:25:59 -07:00
|
|
|
toHaveScreenshot,
|
2021-07-30 16:07:02 -07:00
|
|
|
};
|
|
|
|
|
2022-01-31 18:14:59 -07:00
|
|
|
type ExpectMetaInfo = {
|
2022-03-18 17:31:26 -06:00
|
|
|
message?: string;
|
2022-02-02 19:33:51 -07:00
|
|
|
isSoft: boolean;
|
2022-03-18 17:31:26 -06:00
|
|
|
isPoll: boolean;
|
|
|
|
pollTimeout?: number;
|
2022-01-31 18:14:59 -07:00
|
|
|
};
|
|
|
|
|
|
|
|
let expectCallMetaInfo: undefined|ExpectMetaInfo = undefined;
|
|
|
|
|
|
|
|
class ExpectMetaInfoProxyHandler {
|
2022-03-18 17:31:26 -06:00
|
|
|
private _info: ExpectMetaInfo;
|
2022-01-31 18:14:59 -07:00
|
|
|
|
2022-03-18 17:31:26 -06:00
|
|
|
constructor(messageOrOptions: ExpectMessageOrOptions, isSoft: boolean, isPoll: boolean) {
|
|
|
|
this._info = { isSoft, isPoll };
|
|
|
|
if (typeof messageOrOptions === 'string') {
|
|
|
|
this._info.message = messageOrOptions;
|
|
|
|
} else {
|
|
|
|
this._info.message = messageOrOptions?.message;
|
|
|
|
this._info.pollTimeout = messageOrOptions?.timeout;
|
|
|
|
}
|
2022-01-31 18:14:59 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
get(target: any, prop: any, receiver: any): any {
|
|
|
|
const value = Reflect.get(target, prop, receiver);
|
|
|
|
if (typeof value !== 'function')
|
|
|
|
return new Proxy(value, this);
|
|
|
|
return (...args: any[]) => {
|
2022-02-02 19:33:51 -07:00
|
|
|
const testInfo = currentTestInfo();
|
|
|
|
if (!testInfo)
|
|
|
|
return value.call(target, ...args);
|
|
|
|
const handleError = (e: Error) => {
|
2022-03-18 17:31:26 -06:00
|
|
|
if (this._info.isSoft)
|
2022-02-02 19:33:51 -07:00
|
|
|
testInfo._failWithError(serializeError(e), false /* isHardError */);
|
|
|
|
else
|
|
|
|
throw e;
|
|
|
|
};
|
2022-01-31 18:14:59 -07:00
|
|
|
try {
|
|
|
|
expectCallMetaInfo = {
|
2022-03-18 17:31:26 -06:00
|
|
|
message: this._info.message,
|
|
|
|
isSoft: this._info.isSoft,
|
|
|
|
isPoll: this._info.isPoll,
|
|
|
|
pollTimeout: this._info.pollTimeout,
|
2022-01-31 18:14:59 -07:00
|
|
|
};
|
2022-02-02 19:33:51 -07:00
|
|
|
let result = value.call(target, ...args);
|
|
|
|
if ((result instanceof Promise))
|
|
|
|
result = result.catch(handleError);
|
2022-01-31 18:14:59 -07:00
|
|
|
return result;
|
2022-02-02 19:33:51 -07:00
|
|
|
} catch (e) {
|
|
|
|
handleError(e);
|
2022-01-31 18:14:59 -07:00
|
|
|
} finally {
|
|
|
|
expectCallMetaInfo = undefined;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-18 17:31:26 -06:00
|
|
|
async function pollMatcher(matcher: any, timeout: number, thisArg: any, generator: () => any, ...args: any[]) {
|
|
|
|
let result: { pass: boolean, message: () => string } | undefined = undefined;
|
|
|
|
const startTime = monotonicTime();
|
|
|
|
const pollIntervals = [100, 250, 500];
|
|
|
|
while (true) {
|
|
|
|
const elapsed = monotonicTime() - startTime;
|
|
|
|
if (timeout !== 0 && elapsed > timeout)
|
|
|
|
break;
|
|
|
|
const received = timeout !== 0 ? await raceAgainstTimeout(generator, timeout - elapsed) : await generator();
|
|
|
|
if (received.timedOut)
|
|
|
|
break;
|
|
|
|
result = matcher.call(thisArg, received.result, ...args);
|
|
|
|
const success = result!.pass !== thisArg.isNot;
|
|
|
|
if (success)
|
|
|
|
return result;
|
|
|
|
await new Promise(x => setTimeout(x, pollIntervals.shift() ?? 1000));
|
|
|
|
}
|
|
|
|
const timeoutMessage = `Timeout ${timeout}ms exceeded while waiting on the predicate`;
|
|
|
|
const message = result ? [
|
|
|
|
result.message(),
|
|
|
|
'',
|
|
|
|
`Call Log:`,
|
|
|
|
`- ${timeoutMessage}`,
|
|
|
|
].join('\n') : timeoutMessage;
|
|
|
|
return {
|
|
|
|
pass: thisArg.isNot,
|
|
|
|
message: () => message,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2021-07-30 16:07:02 -07:00
|
|
|
function wrap(matcherName: string, matcher: any) {
|
2022-03-14 19:01:13 -06:00
|
|
|
return function(this: any, ...args: any[]) {
|
2021-07-30 16:07:02 -07:00
|
|
|
const testInfo = currentTestInfo();
|
|
|
|
if (!testInfo)
|
|
|
|
return matcher.call(this, ...args);
|
|
|
|
|
2022-03-14 19:01:13 -06:00
|
|
|
const stackTrace = captureStackTrace();
|
|
|
|
const stackLines = stackTrace.frameTexts;
|
|
|
|
const frame = stackTrace.frames[0];
|
2022-01-31 18:14:59 -07:00
|
|
|
const customMessage = expectCallMetaInfo?.message ?? '';
|
2022-02-02 19:33:51 -07:00
|
|
|
const isSoft = expectCallMetaInfo?.isSoft ?? false;
|
2022-03-18 17:31:26 -06:00
|
|
|
const isPoll = expectCallMetaInfo?.isPoll ?? false;
|
|
|
|
const pollTimeout = expectCallMetaInfo?.pollTimeout;
|
2022-03-30 20:52:00 -08:00
|
|
|
const defaultTitle = `expect${isPoll ? '.poll' : ''}${isSoft ? '.soft' : ''}${this.isNot ? '.not' : ''}.${matcherName}`;
|
2021-09-16 15:51:27 -07:00
|
|
|
const step = testInfo._addStep({
|
2021-10-18 20:06:18 -08:00
|
|
|
location: frame && frame.file ? { file: path.resolve(process.cwd(), frame.file), line: frame.line || 0, column: frame.column || 0 } : undefined,
|
2021-09-16 15:51:27 -07:00
|
|
|
category: 'expect',
|
2022-03-30 20:52:00 -08:00
|
|
|
title: customMessage || defaultTitle,
|
2021-09-16 15:51:27 -07:00
|
|
|
canHaveChildren: true,
|
|
|
|
forceNoParent: false
|
|
|
|
});
|
2021-08-02 17:17:20 -07:00
|
|
|
|
2022-03-30 20:52:00 -08:00
|
|
|
const reportStepEnd = (result: any, options: { refinedTitle?: string }) => {
|
2021-08-02 22:11:37 -07:00
|
|
|
const success = result.pass !== this.isNot;
|
|
|
|
let error: TestError | undefined;
|
2021-08-31 16:34:52 -07:00
|
|
|
if (!success) {
|
|
|
|
const message = result.message();
|
|
|
|
error = { message, stack: message + '\n' + stackLines.join('\n') };
|
2022-01-31 18:14:59 -07:00
|
|
|
if (customMessage) {
|
|
|
|
const messageLines = message.split('\n');
|
|
|
|
// Jest adds something like the following error to all errors:
|
|
|
|
// expect(received).toBe(expected); // Object.is equality
|
|
|
|
const uselessMatcherLineIndex = messageLines.findIndex((line: string) => /expect.*\(.*received.*\)/.test(line));
|
|
|
|
if (uselessMatcherLineIndex !== -1) {
|
|
|
|
// if there's a newline after the matcher text, then remove it as well.
|
|
|
|
if (uselessMatcherLineIndex + 1 < messageLines.length && messageLines[uselessMatcherLineIndex + 1].trim() === '')
|
|
|
|
messageLines.splice(uselessMatcherLineIndex, 2);
|
|
|
|
else
|
|
|
|
messageLines.splice(uselessMatcherLineIndex, 1);
|
|
|
|
}
|
|
|
|
const newMessage = [
|
|
|
|
customMessage,
|
|
|
|
'',
|
|
|
|
...messageLines,
|
|
|
|
].join('\n');
|
|
|
|
result.message = () => newMessage;
|
|
|
|
}
|
2021-08-31 16:34:52 -07:00
|
|
|
}
|
2022-03-30 20:52:00 -08:00
|
|
|
step.complete({ ...options, error });
|
2021-08-02 17:17:20 -07:00
|
|
|
return result;
|
|
|
|
};
|
|
|
|
|
|
|
|
const reportStepError = (error: Error) => {
|
2022-03-30 20:52:00 -08:00
|
|
|
step.complete({ error: serializeError(error) });
|
2021-08-02 17:17:20 -07:00
|
|
|
throw error;
|
|
|
|
};
|
|
|
|
|
2022-03-30 20:52:00 -08:00
|
|
|
const refineTitle = (result: SyncExpectationResult & { titleSuffix?: string }): string | undefined => {
|
|
|
|
return !customMessage && result.titleSuffix ? defaultTitle + result.titleSuffix : undefined;
|
|
|
|
};
|
|
|
|
|
2021-07-30 16:07:02 -07:00
|
|
|
try {
|
2022-03-18 17:31:26 -06:00
|
|
|
let result;
|
|
|
|
const [receivedOrGenerator, ...otherArgs] = args;
|
|
|
|
if (isPoll) {
|
|
|
|
if (typeof receivedOrGenerator !== 'function')
|
|
|
|
throw new Error('`expect.poll()` accepts only function as a first argument');
|
|
|
|
if ((customMatchers as any)[matcherName] || matcherName === 'resolves' || matcherName === 'rejects')
|
|
|
|
throw new Error(`\`expect.poll()\` does not support "${matcherName}" matcher.`);
|
|
|
|
result = pollMatcher(matcher, currentExpectTimeout({ timeout: pollTimeout }), this, receivedOrGenerator, ...otherArgs);
|
|
|
|
} else {
|
|
|
|
if (typeof receivedOrGenerator === 'function')
|
|
|
|
throw new Error('Cannot accept function as a first argument; did you mean to use `expect.poll()`?');
|
|
|
|
result = matcher.call(this, ...args);
|
|
|
|
}
|
2021-08-02 17:17:20 -07:00
|
|
|
if (result instanceof Promise)
|
2022-03-30 20:52:00 -08:00
|
|
|
return result.then(result => reportStepEnd(result, { refinedTitle: refineTitle(result) })).catch(reportStepError);
|
|
|
|
return reportStepEnd(result, { refinedTitle: refineTitle(result) });
|
2021-07-30 16:07:02 -07:00
|
|
|
} catch (e) {
|
2021-08-02 17:17:20 -07:00
|
|
|
reportStepError(e);
|
2021-07-30 16:07:02 -07:00
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
const wrappedMatchers: any = {};
|
|
|
|
for (const matcherName in matchers)
|
|
|
|
wrappedMatchers[matcherName] = wrap(matcherName, matchers[matcherName]);
|
|
|
|
for (const matcherName in customMatchers)
|
|
|
|
wrappedMatchers[matcherName] = wrap(matcherName, (customMatchers as any)[matcherName]);
|
|
|
|
|
|
|
|
expectLibrary.extend(wrappedMatchers);
|