Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sirbrillig/330cb59d4d6d788174fbb294edf09599 to your computer and use it in GitHub Desktop.
Save sirbrillig/330cb59d4d6d788174fbb294edf09599 to your computer and use it in GitHub Desktop.
// This is a little tricky because we need to verify that text never appears,
// even after some time passes, so we use this slightly convoluted technique:
// https://stackoverflow.com/a/68318058/2615868
async function verifyThatTextNeverAppears( text: string ) {
await expect( screen.findByText( text ) ).rejects.toThrow();
}
// OR, a custom Jest matcher:
expect.extend( {
/**
* Assert that a DOM element never appears, even after some time passes.
*
* The argument should be a call to one of testing-library's `findBy...`
* methods which will throw if they do not find a result.
*
* This is an async matcher so you must await its result.
*
* Example:
* `await expect( screen.findByText( 'Bad things' ) ).toNeverAppear();`
*
* This is a little tricky because we need to keep checking over time, so we
* use this slightly convoluted technique:
* https://stackoverflow.com/a/68318058/2615868
*/
async toNeverAppear( elementPromise: Promise< HTMLElement > ) {
let pass = false;
let element = null;
try {
element = await elementPromise;
} catch {
pass = true;
}
if ( pass ) {
return {
message: () => `expected element to appear but it did not.`,
pass: true,
};
}
const elementPretty = element ? prettyDOM( element ) : '';
return {
message: () => `expected element to never appear but it did:\n${ elementPretty }`,
pass: false,
};
},
} );
// Add the above custom Jest assertion to TypeScript.
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace jest {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface Matchers< R > {
toNeverAppear(): Promise< CustomMatcherResult >;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment