Skip to content

Instantly share code, notes, and snippets.

@joanna-liana
Last active September 12, 2021 06:32
Show Gist options
  • Save joanna-liana/3139a6de111f83c7064890779f549190 to your computer and use it in GitHub Desktop.
Save joanna-liana/3139a6de111f83c7064890779f549190 to your computer and use it in GitHub Desktop.
Jest's toBe assertion with custom message (expected value alias)
describe('Assertions with expected value alias', () => {
it('reports the failure with a meaningul message', async () => {
expect(7).toBe(42, 'The Answer to the Ultimate Question of Life, the Universe, and Everything');
});
it('given no custom value alias, it reports the failure with the standard message', async () => {
expect(7).toBe(42);
});
});
import matchers from 'expect/build/matchers.js';
import { printExpected, printReceived } from 'jest-matcher-utils';
const originalToBe = matchers.toBe.bind(matchers);
expect.extend({
toBe(received, expected, expectedValueAlias) {
const {
message: messageFn,
pass
} = originalToBe(received, expected);
if (pass) {
return {
pass: true,
message: messageFn,
};
}
return {
pass: false,
message: (): string => expectedValueAlias ?
`Expected: ${printExpected(`${expectedValueAlias} (${expected})`)}\nGot: ${printReceived(received)}\n\n${messageFn()}` :
messageFn()
};
}
});
module.exports = {
transform: {
'^.+\\.ts?$': 'ts-jest',
},
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.ts?$',
testEnvironment: 'node',
rootDir: '.',
setupFilesAfterEnv: ['./customMatchers.ts']
};
// src/types/jest.d.ts
declare namespace jest {
interface Matchers<R> {
toBe(expectedValue: unknown, expectedValueAlias?: string): CustomMatcherResult;
}
}
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"outDir": "./build",
"allowJs": true,
"target": "esnext",
"esModuleInterop": true,
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true
},
"include": [
"src/types/*.d.ts",
"./src/**/*"
],
"exclude": ["node_modules"]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment