Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve error message when Promise is passed into jest-dom matcher #139

Merged
merged 4 commits into from Jul 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/gentle-colts-pretend.md
@@ -0,0 +1,5 @@
---
'pleasantest': patch
---

Improve error message when Promise is passed into jest-dom matcher
23 changes: 16 additions & 7 deletions src/extend-expect.ts
@@ -1,7 +1,12 @@
import type { ElementHandle, JSHandle } from 'puppeteer';
import { createClientRuntimeServer } from './module-server/client-runtime-server';
import { deserialize, serialize } from './serialize';
import { jsHandleToArray, removeFuncFromStackTrace } from './utils';
import {
isElementHandle,
isPromise,
jsHandleToArray,
removeFuncFromStackTrace,
} from './utils';

const methods = [
'toBeInTheDOM',
Expand Down Expand Up @@ -45,7 +50,7 @@ expect.extend(
...matcherArgs: unknown[]
) {
const serverPromise = createClientRuntimeServer();
if (typeof elementHandle !== 'object' || !elementHandle?.asElement()) {
if (!isElementHandle(elementHandle)) {
// Special case: expect(null).not.toBeInTheDocument() should pass
if (methodName === 'toBeInTheDocument' && this.isNot) {
// This is actually passing but since it is isNot it has to return false
Expand All @@ -62,11 +67,15 @@ expect.extend(
`${this.utils.RECEIVED_COLOR(
'received',
)} value must be an HTMLElement or an SVGElement.`,
this.utils.printWithType(
'Received',
elementHandle,
this.utils.printReceived,
),
isPromise(elementHandle)
? `Received a ${this.utils.RECEIVED_COLOR(
'Promise',
)}. Did you forget to await?`
: this.utils.printWithType(
'Received',
elementHandle,
this.utils.printReceived,
),
].join('\n');
const error = new Error(message);

Expand Down
43 changes: 26 additions & 17 deletions src/utils.ts
Expand Up @@ -15,6 +15,20 @@ export const jsHandleToArray = async (arrayHandle: JSHandle) => {
return arr;
};

export const isPromise = <T extends any>(
input: unknown | Promise<T>,
): input is Promise<T> => Promise.resolve(input) === input; // https://stackoverflow.com/questions/27746304/how-do-i-tell-if-an-object-is-a-promise/38339199#38339199

export const isElementHandle = (input: unknown): input is ElementHandle => {
if (typeof input !== 'object' || !input) return false;
return (input as any).asElement?.() === input;
};

export const isJSHandle = (input: unknown): input is JSHandle => {
if (typeof input !== 'object' || !input) return false;
return 'asElement' in input;
};

export const assertElementHandle: (
input: unknown,
fn: (...params: any[]) => any,
Expand All @@ -25,11 +39,7 @@ export const assertElementHandle: (
messageStart = `element must be an ElementHandle\n\n`,
) => {
const type =
input === null
? 'null'
: typeof input === 'object' && Promise.resolve(input) === input // https://stackoverflow.com/questions/27746304/how-do-i-tell-if-an-object-is-a-promise/38339199#38339199
? 'Promise'
: typeof input;
input === null ? 'null' : isPromise(input) ? 'Promise' : typeof input;

if (type === 'Promise') {
throw removeFuncFromStackTrace(
Expand All @@ -38,20 +48,19 @@ export const assertElementHandle: (
);
}

if (type !== 'object' || input === null || !(input as any).asElement) {
throw removeFuncFromStackTrace(
new Error(`${messageStart}Received ${type}`),
fn,
);
}
if (!isElementHandle(input)) {
// If it is a JSHandle, that points to something _other_ than an element
if (isJSHandle(input)) {
throw removeFuncFromStackTrace(
new Error(
`${messageStart}Received a JSHandle that did not point to an element`,
),
fn,
);
}

// Returns null if it is a JSHandle that does not point to an element
const el = (input as JSHandle).asElement();
if (!el) {
throw removeFuncFromStackTrace(
new Error(
`${messageStart}Received a JSHandle that did not point to an element`,
),
new Error(`${messageStart}Received ${type}`),
fn,
);
}
Expand Down
42 changes: 42 additions & 0 deletions tests/extend-expect.test.ts
@@ -0,0 +1,42 @@
// The matcher test files cover most of the functionality.
// This file checks behavior that is common to all matchers

import { withBrowser } from 'pleasantest';

test(
'throws useful error if Promise is passed',
withBrowser(async ({ screen, utils }) => {
await utils.injectHTML('<h1>Hi</h1>');
await expect(expect(screen.getByText('Hi')).toBeVisible()).rejects
.toThrowErrorMatchingInlineSnapshot(`
"expect(received).toBeVisible()

received value must be an HTMLElement or an SVGElement.
Received a Promise. Did you forget to await?"
calebeby marked this conversation as resolved.
Show resolved Hide resolved
`);
// This short delay is necessary to make sure that the screen.getByText finishes before the test finishes
// Otherwise, the forgot await error is triggered
await new Promise((resolve) => setTimeout(resolve, 100));
}),
);

test(
'throws useful error if non-ElementHandle is passed',
withBrowser(async () => {
await expect(expect(null).toBeVisible()).rejects
.toThrowErrorMatchingInlineSnapshot(`
"expect(received).toBeVisible()

received value must be an HTMLElement or an SVGElement.
Received has value: null"
`);
await expect(expect({}).toBeVisible()).rejects
.toThrowErrorMatchingInlineSnapshot(`
"expect(received).toBeVisible()

received value must be an HTMLElement or an SVGElement.
Received has type: object
Received has value: {}"
`);
}),
);