From de42b740d958e1bb3c1d773acfdc106be2eba805 Mon Sep 17 00:00:00 2001 From: EduardoSCosta Date: Mon, 29 Aug 2022 16:09:00 -0300 Subject: [PATCH 01/13] chore: remove .toThrowError() matcher --- e2e/__tests__/failureDetailsProperty.test.ts | 8 +- .../__tests__/tests.test.js | 2 +- .../__tests__/resolveWithPaths.test.js | 2 +- examples/typescript/__tests__/calc.test.ts | 4 +- .../toThrowMatchers.test.ts.snap | 308 ------- .../expect/src/__tests__/matchers.test.js | 70 +- .../src/__tests__/toThrowMatchers.test.ts | 815 +++++++++--------- packages/expect/src/index.ts | 2 +- packages/expect/src/toThrowMatchers.ts | 1 - packages/expect/src/types.ts | 4 - .../circusItFailingTestError.test.ts | 14 +- .../src/__tests__/circusItTestError.test.ts | 16 +- .../__tests__/circusItTodoTestError.test.ts | 6 +- .../src/__tests__/hooksError.test.ts | 4 +- .../src/__tests__/normalize.test.ts | 10 +- .../src/__tests__/readConfig.test.ts | 2 +- .../src/__tests__/readConfigs.test.ts | 2 +- .../src/__tests__/resolveConfigPath.test.ts | 16 +- .../src/__tests__/stringToBytes.test.ts | 12 +- .../jest-core/src/__tests__/watch.test.js | 4 +- .../jest-each/src/__tests__/template.test.ts | 6 +- packages/jest-globals/src/__tests__/index.ts | 2 +- .../src/__tests__/hooksError.test.ts | 4 +- .../src/__tests__/itTestError.test.ts | 12 +- .../src/__tests__/todoError.test.ts | 6 +- .../__tests__/runtime_require_module.test.js | 4 +- .../runtime_require_module_or_mock.test.js | 6 +- .../src/__tests__/InlineSnapshots.test.ts | 4 +- .../jest-snapshot/src/__tests__/utils.test.ts | 8 +- .../jest-types/__typetests__/expect.test.ts | 6 - .../convertDescriptorToString.test.ts | 2 +- .../workers/__tests__/WorkerEdgeCases.test.js | 6 +- 32 files changed, 516 insertions(+), 852 deletions(-) diff --git a/e2e/__tests__/failureDetailsProperty.test.ts b/e2e/__tests__/failureDetailsProperty.test.ts index c7a7144c6116..c13bd10d40f8 100644 --- a/e2e/__tests__/failureDetailsProperty.test.ts +++ b/e2e/__tests__/failureDetailsProperty.test.ts @@ -160,19 +160,19 @@ test('that the failureDetails property is set', () => { Object { "actual": "", "error": Object { - "message": "expect(received).rejects.toThrowError() + "message": "expect(received).rejects.toThrow() Received promise resolved instead of rejected Resolved to value: 1", }, "expected": "", "matcherName": "", - "message": "Error: expect(received).rejects.toThrowError() + "message": "Error: expect(received).rejects.toThrow() Received promise resolved instead of rejected Resolved to value: 1", "passed": false, - "stack": "Error: expect(received).rejects.toThrowError() + "stack": "Error: expect(received).rejects.toThrow() Received promise resolved instead of rejected Resolved to value: 1 @@ -245,7 +245,7 @@ test('that the failureDetails property is set', () => { ], Array [ Object { - "message": "expect(received).rejects.toThrowError() + "message": "expect(received).rejects.toThrow() Received promise resolved instead of rejected Resolved to value: 1", diff --git a/e2e/failureDetails-property/__tests__/tests.test.js b/e2e/failureDetails-property/__tests__/tests.test.js index 4602fe51c60b..58cc89cc6968 100644 --- a/e2e/failureDetails-property/__tests__/tests.test.js +++ b/e2e/failureDetails-property/__tests__/tests.test.js @@ -33,5 +33,5 @@ it('throws!', () => { }); test('promise rejection', async () => { - await expect(Promise.resolve(1)).rejects.toThrowError(); + await expect(Promise.resolve(1)).rejects.toThrow(); }); diff --git a/e2e/resolve-with-paths/__tests__/resolveWithPaths.test.js b/e2e/resolve-with-paths/__tests__/resolveWithPaths.test.js index 5e7950a90503..04121c1c263c 100644 --- a/e2e/resolve-with-paths/__tests__/resolveWithPaths.test.js +++ b/e2e/resolve-with-paths/__tests__/resolveWithPaths.test.js @@ -30,7 +30,7 @@ test('finds a native node module when paths are given', () => { }); test('throws an error if the module cannot be found from given paths', () => { - expect(() => require.resolve('./mod.js', {paths: ['..']})).toThrowError( + expect(() => require.resolve('./mod.js', {paths: ['..']})).toThrow( "Cannot resolve module './mod.js' from paths ['..'] from ", ); }); diff --git a/examples/typescript/__tests__/calc.test.ts b/examples/typescript/__tests__/calc.test.ts index 7a05eadd8757..817bbb86f9fe 100644 --- a/examples/typescript/__tests__/calc.test.ts +++ b/examples/typescript/__tests__/calc.test.ts @@ -85,8 +85,6 @@ describe('calc - mocks', () => { const calc = makeCalc(memory); // @ts-expect-error - expect(() => calc('Multiply', [2, 3])).toThrowError( - new Error('Invalid op'), - ); + expect(() => calc('Multiply', [2, 3])).toThrow(new Error('Invalid op')); }); }); diff --git a/packages/expect/src/__tests__/__snapshots__/toThrowMatchers.test.ts.snap b/packages/expect/src/__tests__/__snapshots__/toThrowMatchers.test.ts.snap index 0b2df1702e07..1c54deebd0e5 100644 --- a/packages/expect/src/__tests__/__snapshots__/toThrowMatchers.test.ts.snap +++ b/packages/expect/src/__tests__/__snapshots__/toThrowMatchers.test.ts.snap @@ -307,311 +307,3 @@ Expected substring: not "Server Error" Received value: "Internal Server Error" `; - -exports[`toThrowError asymmetric any-Class fail isNot false 1`] = ` -expect(received).toThrowError(expected) - -Expected asymmetric matcher: Any - -Received name: "Error" -Received message: "apple" - - at jestExpect (packages/expect/src/__tests__/toThrowMatchers-test.js:24:74) -`; - -exports[`toThrowError asymmetric any-Class fail isNot true 1`] = ` -expect(received).not.toThrowError(expected) - -Expected asymmetric matcher: not Any - -Received name: "Error" -Received message: "apple" - - at jestExpect (packages/expect/src/__tests__/toThrowMatchers-test.js:24:74) -`; - -exports[`toThrowError asymmetric anything fail isNot false 1`] = ` -expect(received).toThrowError(expected) - -Expected asymmetric matcher: Anything - -Thrown value: null - -`; - -exports[`toThrowError asymmetric anything fail isNot true 1`] = ` -expect(received).not.toThrowError(expected) - -Expected asymmetric matcher: not Anything - -Received name: "Error" -Received message: "apple" - - at jestExpect (packages/expect/src/__tests__/toThrowMatchers-test.js:24:74) -`; - -exports[`toThrowError asymmetric no-symbol fail isNot false 1`] = ` -expect(received).toThrowError(expected) - -Expected asymmetric matcher: {"asymmetricMatch": [Function asymmetricMatch]} - -Received name: "Error" -Received message: "apple" - - at jestExpect (packages/expect/src/__tests__/toThrowMatchers-test.js:24:74) -`; - -exports[`toThrowError asymmetric no-symbol fail isNot true 1`] = ` -expect(received).not.toThrowError(expected) - -Expected asymmetric matcher: not {"asymmetricMatch": [Function asymmetricMatch]} - -Received name: "Error" -Received message: "apple" - - at jestExpect (packages/expect/src/__tests__/toThrowMatchers-test.js:24:74) -`; - -exports[`toThrowError asymmetric objectContaining fail isNot false 1`] = ` -expect(received).toThrowError(expected) - -Expected asymmetric matcher: ObjectContaining {"name": "NotError"} - -Received name: "Error" -Received message: "apple" - - at jestExpect (packages/expect/src/__tests__/toThrowMatchers-test.js:24:74) -`; - -exports[`toThrowError asymmetric objectContaining fail isNot true 1`] = ` -expect(received).not.toThrowError(expected) - -Expected asymmetric matcher: not ObjectContaining {"name": "Error"} - -Received name: "Error" -Received message: "apple" - - at jestExpect (packages/expect/src/__tests__/toThrowMatchers-test.js:24:74) -`; - -exports[`toThrowError error class did not throw at all 1`] = ` -expect(received).toThrowError(expected) - -Expected constructor: Err - -Received function did not throw -`; - -exports[`toThrowError error class threw, but class did not match (error) 1`] = ` -expect(received).toThrowError(expected) - -Expected constructor: Err2 -Received constructor: Err - -Received message: "apple" - - at jestExpect (packages/expect/src/__tests__/toThrowMatchers-test.js:24:74) -`; - -exports[`toThrowError error class threw, but class did not match (non-error falsey) 1`] = ` -expect(received).toThrowError(expected) - -Expected constructor: Err2 - -Received value: undefined - -`; - -exports[`toThrowError error class threw, but class should not match (error subclass) 1`] = ` -expect(received).not.toThrowError(expected) - -Expected constructor: not Err -Received constructor: SubErr extends Err - -Received message: "apple" - - at jestExpect (packages/expect/src/__tests__/toThrowMatchers-test.js:24:74) -`; - -exports[`toThrowError error class threw, but class should not match (error subsubclass) 1`] = ` -expect(received).not.toThrowError(expected) - -Expected constructor: not Err -Received constructor: SubSubErr extends … extends Err - -Received message: "apple" - - at jestExpect (packages/expect/src/__tests__/toThrowMatchers-test.js:24:74) -`; - -exports[`toThrowError error class threw, but class should not match (error) 1`] = ` -expect(received).not.toThrowError(expected) - -Expected constructor: not Err - -Received message: "apple" - - at jestExpect (packages/expect/src/__tests__/toThrowMatchers-test.js:24:74) -`; - -exports[`toThrowError error-message fail isNot false 1`] = ` -expect(received).toThrowError(expected) - -Expected message: "apple" -Received message: "banana" - -`; - -exports[`toThrowError error-message fail isNot true 1`] = ` -expect(received).not.toThrowError(expected) - -Expected message: not "Invalid array length" - -`; - -exports[`toThrowError error-message fail multiline diff highlight incorrect expected space 1`] = ` -expect(received).toThrowError(expected) - -- Expected message - 1 -+ Received message + 1 - -- There is no route defined for key Settings. -+ There is no route defined for key Settings. - Must be one of: 'Home' - -`; - -exports[`toThrowError expected is undefined threw, but should not have (non-error falsey) 1`] = ` -expect(received).not.toThrowError() - -Thrown value: null - -`; - -exports[`toThrowError invalid actual 1`] = ` -expect(received).toThrowError() - -Matcher error: received value must be a function - -Received has type: string -Received has value: "a string" -`; - -exports[`toThrowError invalid arguments 1`] = ` -expect(received).not.toThrowError(expected) - -Matcher error: expected value must be a string or regular expression or class or error - -Expected has type: number -Expected has value: 111 -`; - -exports[`toThrowError promise/async throws if Error-like object is returned did not throw at all 1`] = ` -expect(received).rejects.toThrowError() - -Received function did not throw -`; - -exports[`toThrowError promise/async throws if Error-like object is returned threw, but class did not match 1`] = ` -expect(received).rejects.toThrowError(expected) - -Expected constructor: Err2 -Received constructor: Err - -Received message: "async apple" - - at jestExpect (packages/expect/src/__tests__/toThrowMatchers-test.js:24:74) -`; - -exports[`toThrowError promise/async throws if Error-like object is returned threw, but should not have 1`] = ` -expect(received).rejects.not.toThrowError() - -Error name: "Error" -Error message: "async apple" - - at jestExpect (packages/expect/src/__tests__/toThrowMatchers-test.js:24:74) -`; - -exports[`toThrowError regexp did not throw at all 1`] = ` -expect(received).toThrowError(expected) - -Expected pattern: /apple/ - -Received function did not throw -`; - -exports[`toThrowError regexp threw, but message did not match (error) 1`] = ` -expect(received).toThrowError(expected) - -Expected pattern: /banana/ -Received message: "apple" - - at jestExpect (packages/expect/src/__tests__/toThrowMatchers-test.js:24:74) -`; - -exports[`toThrowError regexp threw, but message did not match (non-error falsey) 1`] = ` -expect(received).toThrowError(expected) - -Expected pattern: /^[123456789]\\d*/ -Received value: 0 - -`; - -exports[`toThrowError regexp threw, but message should not match (error) 1`] = ` -expect(received).not.toThrowError(expected) - -Expected pattern: not / array / -Received message: "Invalid array length" - - at jestExpect (packages/expect/src/__tests__/toThrowMatchers-test.js:24:74) -`; - -exports[`toThrowError regexp threw, but message should not match (non-error truthy) 1`] = ` -expect(received).not.toThrowError(expected) - -Expected pattern: not /^[123456789]\\d*/ -Received value: 404 - -`; - -exports[`toThrowError substring did not throw at all 1`] = ` -expect(received).toThrowError(expected) - -Expected substring: "apple" - -Received function did not throw -`; - -exports[`toThrowError substring threw, but message did not match (error) 1`] = ` -expect(received).toThrowError(expected) - -Expected substring: "banana" -Received message: "apple" - - at jestExpect (packages/expect/src/__tests__/toThrowMatchers-test.js:24:74) -`; - -exports[`toThrowError substring threw, but message did not match (non-error falsey) 1`] = ` -expect(received).toThrowError(expected) - -Expected substring: "Server Error" -Received value: "" - -`; - -exports[`toThrowError substring threw, but message should not match (error) 1`] = ` -expect(received).not.toThrowError(expected) - -Expected substring: not "array" -Received message: "Invalid array length" - - at jestExpect (packages/expect/src/__tests__/toThrowMatchers-test.js:24:74) -`; - -exports[`toThrowError substring threw, but message should not match (non-error truthy) 1`] = ` -expect(received).not.toThrowError(expected) - -Expected substring: not "Server Error" -Received value: "Internal Server Error" - -`; diff --git a/packages/expect/src/__tests__/matchers.test.js b/packages/expect/src/__tests__/matchers.test.js index 2dc7c6656e08..d79f62b7cafb 100644 --- a/packages/expect/src/__tests__/matchers.test.js +++ b/packages/expect/src/__tests__/matchers.test.js @@ -254,7 +254,7 @@ describe('.toBe()', () => { [{a: BigInt(1)}, {a: BigInt(1)}], ].forEach(([a, b]) => { it(`fails for: ${stringify(a)} and ${stringify(b)}`, () => { - expect(() => jestExpect(a).toBe(b)).toThrowError('toBe'); + expect(() => jestExpect(a).toBe(b)).toThrow('toBe'); }); }); @@ -266,7 +266,7 @@ describe('.toBe()', () => { [BigInt(1), BigInt('1')].forEach(v => { it(`fails for '${stringify(v)}' with '.not'`, () => { - expect(() => jestExpect(v).not.toBe(v)).toThrowError('toBe'); + expect(() => jestExpect(v).not.toBe(v)).toThrow('toBe'); }); }); @@ -699,7 +699,7 @@ describe('.toEqual()', () => { test(`{pass: false} expect(${stringify(a)}).toEqual(${stringify( b, )})`, () => { - expect(() => jestExpect(a).toEqual(b)).toThrowError('toEqual'); + expect(() => jestExpect(a).toEqual(b)).toThrow('toEqual'); jestExpect(a).not.toEqual(b); }); }); @@ -953,7 +953,7 @@ describe('.toEqual()', () => { b, )})`, () => { jestExpect(a).toEqual(b); - expect(() => jestExpect(a).not.toEqual(b)).toThrowError('toEqual'); + expect(() => jestExpect(a).not.toEqual(b)).toThrow('toEqual'); }); }); @@ -1165,9 +1165,9 @@ describe('.toBeTruthy(), .toBeFalsy()', () => { jestExpect(v).toBeTruthy(); jestExpect(v).not.toBeFalsy(); - expect(() => jestExpect(v).not.toBeTruthy()).toThrowError('toBeTruthy'); + expect(() => jestExpect(v).not.toBeTruthy()).toThrow('toBeTruthy'); - expect(() => jestExpect(v).toBeFalsy()).toThrowError('toBeFalsy'); + expect(() => jestExpect(v).toBeFalsy()).toThrow('toBeFalsy'); }); }); @@ -1189,9 +1189,9 @@ describe('.toBeTruthy(), .toBeFalsy()', () => { jestExpect(v).toBeFalsy(); jestExpect(v).not.toBeTruthy(); - expect(() => jestExpect(v).toBeTruthy()).toThrowError('toBeTruthy'); + expect(() => jestExpect(v).toBeTruthy()).toThrow('toBeTruthy'); - expect(() => jestExpect(v).not.toBeFalsy()).toThrowError('toBeFalsy'); + expect(() => jestExpect(v).not.toBeFalsy()).toThrow('toBeFalsy'); }); }); }); @@ -1255,9 +1255,9 @@ describe('.toBeDefined(), .toBeUndefined()', () => { jestExpect(v).toBeDefined(); jestExpect(v).not.toBeUndefined(); - expect(() => jestExpect(v).not.toBeDefined()).toThrowError('toBeDefined'); + expect(() => jestExpect(v).not.toBeDefined()).toThrow('toBeDefined'); - expect(() => jestExpect(v).toBeUndefined()).toThrowError('toBeUndefined'); + expect(() => jestExpect(v).toBeUndefined()).toThrow('toBeUndefined'); }); }); @@ -1417,35 +1417,35 @@ describe( }); it(`throws: [${stringify(small)}, ${stringify(big)}]`, () => { - expect(() => jestExpect(small).toBeGreaterThan(big)).toThrowError( + expect(() => jestExpect(small).toBeGreaterThan(big)).toThrow( 'toBeGreaterThan', ); - expect(() => jestExpect(small).not.toBeLessThan(big)).toThrowError( + expect(() => jestExpect(small).not.toBeLessThan(big)).toThrow( 'toBeLessThan', ); - expect(() => jestExpect(big).not.toBeGreaterThan(small)).toThrowError( + expect(() => jestExpect(big).not.toBeGreaterThan(small)).toThrow( 'toBeGreaterThan', ); - expect(() => jestExpect(big).toBeLessThan(small)).toThrowError( + expect(() => jestExpect(big).toBeLessThan(small)).toThrow( 'toBeLessThan', ); - expect(() => - jestExpect(small).toBeGreaterThanOrEqual(big), - ).toThrowError('toBeGreaterThanOrEqual'); + expect(() => jestExpect(small).toBeGreaterThanOrEqual(big)).toThrow( + 'toBeGreaterThanOrEqual', + ); - expect(() => - jestExpect(small).not.toBeLessThanOrEqual(big), - ).toThrowError('toBeLessThanOrEqual'); + expect(() => jestExpect(small).not.toBeLessThanOrEqual(big)).toThrow( + 'toBeLessThanOrEqual', + ); - expect(() => - jestExpect(big).not.toBeGreaterThanOrEqual(small), - ).toThrowError('toBeGreaterThanOrEqual'); + expect(() => jestExpect(big).not.toBeGreaterThanOrEqual(small)).toThrow( + 'toBeGreaterThanOrEqual', + ); - expect(() => jestExpect(big).toBeLessThanOrEqual(small)).toThrowError( + expect(() => jestExpect(big).toBeLessThanOrEqual(small)).toThrow( 'toBeLessThanOrEqual', ); }); @@ -1480,11 +1480,11 @@ describe( jestExpect(n1).toBeGreaterThanOrEqual(n2); jestExpect(n1).toBeLessThanOrEqual(n2); - expect(() => - jestExpect(n1).not.toBeGreaterThanOrEqual(n2), - ).toThrowError('toBeGreaterThanOrEqual'); + expect(() => jestExpect(n1).not.toBeGreaterThanOrEqual(n2)).toThrow( + 'toBeGreaterThanOrEqual', + ); - expect(() => jestExpect(n1).not.toBeLessThanOrEqual(n2)).toThrowError( + expect(() => jestExpect(n1).not.toBeLessThanOrEqual(n2)).toThrow( 'toBeLessThanOrEqual', ); }); @@ -1510,10 +1510,8 @@ describe('.toContain(), .toContainEqual()', () => { jestExpect(iterable).toContain(2); jestExpect(iterable).toContainEqual(2); - expect(() => jestExpect(iterable).not.toContain(1)).toThrowError( - 'toContain', - ); - expect(() => jestExpect(iterable).not.toContainEqual(1)).toThrowError( + expect(() => jestExpect(iterable).not.toContain(1)).toThrow('toContain'); + expect(() => jestExpect(iterable).not.toContainEqual(1)).toThrow( 'toContainEqual', ); }); @@ -1545,7 +1543,7 @@ describe('.toContain(), .toContainEqual()', () => { it(`'${stringify(list)}' contains '${stringify(v)}'`, () => { jestExpect(list).toContain(v); - expect(() => jestExpect(list).not.toContain(v)).toThrowError('toContain'); + expect(() => jestExpect(list).not.toContain(v)).toThrow('toContain'); }); }); @@ -1568,7 +1566,7 @@ describe('.toContain(), .toContainEqual()', () => { it(`'${stringify(list)}' does not contain '${stringify(v)}'`, () => { jestExpect(list).not.toContain(v); - expect(() => jestExpect(list).toContain(v)).toThrowError('toContain'); + expect(() => jestExpect(list).toContain(v)).toThrow('toContain'); }); }); @@ -1584,9 +1582,7 @@ describe('.toContain(), .toContainEqual()', () => { expect(() => jestExpect('false').toContain(false), ).toThrowErrorMatchingSnapshot(); - expect(() => jestExpect('1').toContain(BigInt(1))).toThrowError( - 'toContain', - ); + expect(() => jestExpect('1').toContain(BigInt(1))).toThrow('toContain'); }); [ diff --git a/packages/expect/src/__tests__/toThrowMatchers.test.ts b/packages/expect/src/__tests__/toThrowMatchers.test.ts index 650193f0e26d..8402c28f1946 100644 --- a/packages/expect/src/__tests__/toThrowMatchers.test.ts +++ b/packages/expect/src/__tests__/toThrowMatchers.test.ts @@ -22,232 +22,277 @@ class CustomError extends Error { } } -// `as const` needs newer babel which explodes on node 6 -const matchers: ['toThrowError', 'toThrow'] = ['toThrowError', 'toThrow']; - -matchers.forEach(toThrow => { - describe(toThrow, () => { - class Err extends CustomError {} - class Err2 extends CustomError {} +describe('toThrow', () => { + class Err extends CustomError {} + class Err2 extends CustomError {} + + test('to throw or not to throw', () => { + jestExpect(() => { + throw new CustomError('apple'); + }).toThrow(); + jestExpect(() => {}).not.toThrow(); + }); - test('to throw or not to throw', () => { + describe('substring', () => { + it('passes', () => { jestExpect(() => { throw new CustomError('apple'); - })[toThrow](); - jestExpect(() => {}).not[toThrow](); + }).toThrow('apple'); + jestExpect(() => { + throw new CustomError('banana'); + }).not.toThrow('apple'); + jestExpect(() => {}).not.toThrow('apple'); + }); + + test('did not throw at all', () => { + expect(() => + jestExpect(() => {}).toThrow('apple'), + ).toThrowErrorMatchingSnapshot(); }); - describe('substring', () => { - it('passes', () => { + test('threw, but message did not match (error)', () => { + expect(() => { jestExpect(() => { throw new CustomError('apple'); - })[toThrow]('apple'); - jestExpect(() => { - throw new CustomError('banana'); - }).not[toThrow]('apple'); - jestExpect(() => {}).not[toThrow]('apple'); - }); + }).toThrow('banana'); + }).toThrowErrorMatchingSnapshot(); + }); - test('did not throw at all', () => { - expect(() => - jestExpect(() => {})[toThrow]('apple'), - ).toThrowErrorMatchingSnapshot(); - }); + test('threw, but message did not match (non-error falsey)', () => { + expect(() => { + jestExpect(() => { + // eslint-disable-next-line no-throw-literal + throw ''; + }).toThrow('Server Error'); + }).toThrowErrorMatchingSnapshot(); + }); - test('threw, but message did not match (error)', () => { - expect(() => { - jestExpect(() => { - throw new CustomError('apple'); - })[toThrow]('banana'); - }).toThrowErrorMatchingSnapshot(); - }); + it('properly escapes strings when matching against errors', () => { + jestExpect(() => { + throw new TypeError('"this"? throws.'); + }).toThrow('"this"? throws.'); + }); - test('threw, but message did not match (non-error falsey)', () => { - expect(() => { - jestExpect(() => { - // eslint-disable-next-line no-throw-literal - throw ''; - })[toThrow]('Server Error'); - }).toThrowErrorMatchingSnapshot(); - }); + test('threw, but message should not match (error)', () => { + expect(() => { + jestExpect(() => { + throw new CustomError('Invalid array length'); + }).not.toThrow('array'); + }).toThrowErrorMatchingSnapshot(); + }); - it('properly escapes strings when matching against errors', () => { + test('threw, but message should not match (non-error truthy)', () => { + expect(() => { jestExpect(() => { - throw new TypeError('"this"? throws.'); - })[toThrow]('"this"? throws.'); - }); + // eslint-disable-next-line no-throw-literal + throw 'Internal Server Error'; + }).not.toThrow('Server Error'); + }).toThrowErrorMatchingSnapshot(); + }); + }); - test('threw, but message should not match (error)', () => { - expect(() => { - jestExpect(() => { - throw new CustomError('Invalid array length'); - }).not[toThrow]('array'); - }).toThrowErrorMatchingSnapshot(); - }); + describe('regexp', () => { + it('passes', () => { + jestExpect(() => { + throw new CustomError('apple'); + }).toThrow(/apple/); + jestExpect(() => { + throw new CustomError('banana'); + }).not.toThrow(/apple/); + jestExpect(() => {}).not.toThrow(/apple/); + }); - test('threw, but message should not match (non-error truthy)', () => { - expect(() => { - jestExpect(() => { - // eslint-disable-next-line no-throw-literal - throw 'Internal Server Error'; - }).not[toThrow]('Server Error'); - }).toThrowErrorMatchingSnapshot(); - }); + test('did not throw at all', () => { + expect(() => + jestExpect(() => {}).toThrow(/apple/), + ).toThrowErrorMatchingSnapshot(); }); - describe('regexp', () => { - it('passes', () => { + test('threw, but message did not match (error)', () => { + expect(() => { jestExpect(() => { throw new CustomError('apple'); - })[toThrow](/apple/); + }).toThrow(/banana/); + }).toThrowErrorMatchingSnapshot(); + }); + + test('threw, but message did not match (non-error falsey)', () => { + expect(() => { jestExpect(() => { - throw new CustomError('banana'); - }).not[toThrow](/apple/); - jestExpect(() => {}).not[toThrow](/apple/); - }); + // eslint-disable-next-line no-throw-literal + throw 0; + }).toThrow(/^[123456789]\d*/); + }).toThrowErrorMatchingSnapshot(); + }); - test('did not throw at all', () => { - expect(() => - jestExpect(() => {})[toThrow](/apple/), - ).toThrowErrorMatchingSnapshot(); - }); + test('threw, but message should not match (error)', () => { + expect(() => { + jestExpect(() => { + throw new CustomError('Invalid array length'); + }).not.toThrow(/ array /); + }).toThrowErrorMatchingSnapshot(); + }); - test('threw, but message did not match (error)', () => { - expect(() => { - jestExpect(() => { - throw new CustomError('apple'); - })[toThrow](/banana/); - }).toThrowErrorMatchingSnapshot(); - }); + test('threw, but message should not match (non-error truthy)', () => { + expect(() => { + jestExpect(() => { + // eslint-disable-next-line no-throw-literal + throw 404; + }).not.toThrow(/^[123456789]\d*/); + }).toThrowErrorMatchingSnapshot(); + }); + }); - test('threw, but message did not match (non-error falsey)', () => { - expect(() => { - jestExpect(() => { - // eslint-disable-next-line no-throw-literal - throw 0; - })[toThrow](/^[123456789]\d*/); - }).toThrowErrorMatchingSnapshot(); - }); + describe('error class', () => { + class SubErr extends Err { + constructor(message?: string) { + super(message); + // In a carefully written error subclass, + // name property is equal to constructor name. + this.name = this.constructor.name; + } + } + + class SubSubErr extends SubErr { + constructor(message?: string) { + super(message); + // In a carefully written error subclass, + // name property is equal to constructor name. + this.name = this.constructor.name; + } + } - test('threw, but message should not match (error)', () => { - expect(() => { - jestExpect(() => { - throw new CustomError('Invalid array length'); - }).not[toThrow](/ array /); - }).toThrowErrorMatchingSnapshot(); - }); + it('passes', () => { + jestExpect(() => { + throw new Err(); + }).toThrow(Err); + jestExpect(() => { + throw new Err(); + }).toThrow(CustomError); + jestExpect(() => { + throw new Err(); + }).not.toThrow(Err2); + jestExpect(() => {}).not.toThrow(Err); + }); - test('threw, but message should not match (non-error truthy)', () => { - expect(() => { - jestExpect(() => { - // eslint-disable-next-line no-throw-literal - throw 404; - }).not[toThrow](/^[123456789]\d*/); - }).toThrowErrorMatchingSnapshot(); - }); + test('did not throw at all', () => { + expect(() => + expect(() => {}).toThrow(Err), + ).toThrowErrorMatchingSnapshot(); }); - describe('error class', () => { - class SubErr extends Err { - constructor(message?: string) { - super(message); - // In a carefully written error subclass, - // name property is equal to constructor name. - this.name = this.constructor.name; - } - } + test('threw, but class did not match (error)', () => { + expect(() => { + jestExpect(() => { + throw new Err('apple'); + }).toThrow(Err2); + }).toThrowErrorMatchingSnapshot(); + }); - class SubSubErr extends SubErr { - constructor(message?: string) { - super(message); - // In a carefully written error subclass, - // name property is equal to constructor name. - this.name = this.constructor.name; - } - } + test('threw, but class did not match (non-error falsey)', () => { + expect(() => { + jestExpect(() => { + // eslint-disable-next-line no-throw-literal + throw undefined; + }).toThrow(Err2); + }).toThrowErrorMatchingSnapshot(); + }); - it('passes', () => { + test('threw, but class should not match (error)', () => { + expect(() => { jestExpect(() => { - throw new Err(); - })[toThrow](Err); + throw new Err('apple'); + }).not.toThrow(Err); + }).toThrowErrorMatchingSnapshot(); + }); + + test('threw, but class should not match (error subclass)', () => { + expect(() => { jestExpect(() => { - throw new Err(); - })[toThrow](CustomError); + throw new SubErr('apple'); + }).not.toThrow(Err); + }).toThrowErrorMatchingSnapshot(); + }); + + test('threw, but class should not match (error subsubclass)', () => { + expect(() => { jestExpect(() => { - throw new Err(); - }).not[toThrow](Err2); - jestExpect(() => {}).not[toThrow](Err); - }); + throw new SubSubErr('apple'); + }).not.toThrow(Err); + }).toThrowErrorMatchingSnapshot(); + }); + }); - test('did not throw at all', () => { - expect(() => - expect(() => {})[toThrow](Err), - ).toThrowErrorMatchingSnapshot(); - }); + describe('error-message', () => { + // Received message in report if object has message property. + class ErrorMessage { + // not extending Error! + constructor(message) { + this.message = message; + } + } + const expected = new ErrorMessage('apple'); - test('threw, but class did not match (error)', () => { - expect(() => { - jestExpect(() => { - throw new Err('apple'); - })[toThrow](Err2); - }).toThrowErrorMatchingSnapshot(); + describe('pass', () => { + test('isNot false', () => { + jestExpect(() => { + throw new ErrorMessage('apple'); + }).toThrow(expected); }); - test('threw, but class did not match (non-error falsey)', () => { - expect(() => { - jestExpect(() => { - // eslint-disable-next-line no-throw-literal - throw undefined; - })[toThrow](Err2); - }).toThrowErrorMatchingSnapshot(); + test('isNot true', () => { + jestExpect(() => { + throw new ErrorMessage('banana'); + }).not.toThrow(expected); }); + }); - test('threw, but class should not match (error)', () => { - expect(() => { + describe('fail', () => { + test('isNot false', () => { + expect(() => jestExpect(() => { - throw new Err('apple'); - }).not[toThrow](Err); - }).toThrowErrorMatchingSnapshot(); + throw new ErrorMessage('banana'); + }).toThrow(expected), + ).toThrowErrorMatchingSnapshot(); }); - test('threw, but class should not match (error subclass)', () => { - expect(() => { + test('isNot true', () => { + const message = 'Invalid array length'; + expect(() => jestExpect(() => { - throw new SubErr('apple'); - }).not[toThrow](Err); - }).toThrowErrorMatchingSnapshot(); + throw new ErrorMessage(message); + }).not.toThrow({message}), + ).toThrowErrorMatchingSnapshot(); }); - test('threw, but class should not match (error subsubclass)', () => { - expect(() => { + test('multiline diff highlight incorrect expected space', () => { + // jest/issues/2673 + const a = + "There is no route defined for key Settings. \nMust be one of: 'Home'"; + const b = + "There is no route defined for key Settings.\nMust be one of: 'Home'"; + expect(() => jestExpect(() => { - throw new SubSubErr('apple'); - }).not[toThrow](Err); - }).toThrowErrorMatchingSnapshot(); + throw new ErrorMessage(b); + }).toThrow({message: a}), + ).toThrowErrorMatchingSnapshot(); }); }); + }); - describe('error-message', () => { - // Received message in report if object has message property. - class ErrorMessage { - // not extending Error! - constructor(message) { - this.message = message; - } - } - const expected = new ErrorMessage('apple'); - + describe('asymmetric', () => { + describe('any-Class', () => { describe('pass', () => { test('isNot false', () => { jestExpect(() => { - throw new ErrorMessage('apple'); - })[toThrow](expected); + throw new Err('apple'); + }).toThrow(expect.any(Err)); }); test('isNot true', () => { jestExpect(() => { - throw new ErrorMessage('banana'); - }).not[toThrow](expected); + throw new Err('apple'); + }).not.toThrow(expect.any(Err2)); }); }); @@ -255,296 +300,246 @@ matchers.forEach(toThrow => { test('isNot false', () => { expect(() => jestExpect(() => { - throw new ErrorMessage('banana'); - })[toThrow](expected), + throw new Err('apple'); + }).toThrow(expect.any(Err2)), ).toThrowErrorMatchingSnapshot(); }); test('isNot true', () => { - const message = 'Invalid array length'; - expect(() => - jestExpect(() => { - throw new ErrorMessage(message); - }).not[toThrow]({message}), - ).toThrowErrorMatchingSnapshot(); - }); - - test('multiline diff highlight incorrect expected space', () => { - // jest/issues/2673 - const a = - "There is no route defined for key Settings. \nMust be one of: 'Home'"; - const b = - "There is no route defined for key Settings.\nMust be one of: 'Home'"; expect(() => jestExpect(() => { - throw new ErrorMessage(b); - })[toThrow]({message: a}), + throw new Err('apple'); + }).not.toThrow(expect.any(Err)), ).toThrowErrorMatchingSnapshot(); }); }); }); - describe('asymmetric', () => { - describe('any-Class', () => { - describe('pass', () => { - test('isNot false', () => { - jestExpect(() => { - throw new Err('apple'); - })[toThrow](expect.any(Err)); - }); - - test('isNot true', () => { - jestExpect(() => { - throw new Err('apple'); - }).not[toThrow](expect.any(Err2)); - }); + describe('anything', () => { + describe('pass', () => { + test('isNot false', () => { + jestExpect(() => { + throw new CustomError('apple'); + }).toThrow(expect.anything()); }); - describe('fail', () => { - test('isNot false', () => { - expect(() => - jestExpect(() => { - throw new Err('apple'); - })[toThrow](expect.any(Err2)), - ).toThrowErrorMatchingSnapshot(); - }); - - test('isNot true', () => { - expect(() => - jestExpect(() => { - throw new Err('apple'); - }).not[toThrow](expect.any(Err)), - ).toThrowErrorMatchingSnapshot(); - }); + test('isNot true', () => { + jestExpect(() => {}).not.toThrow(expect.anything()); + jestExpect(() => { + // eslint-disable-next-line no-throw-literal + throw null; + }).not.toThrow(expect.anything()); }); }); - describe('anything', () => { - describe('pass', () => { - test('isNot false', () => { - jestExpect(() => { - throw new CustomError('apple'); - })[toThrow](expect.anything()); - }); - - test('isNot true', () => { - jestExpect(() => {}).not[toThrow](expect.anything()); + describe('fail', () => { + test('isNot false', () => { + expect(() => jestExpect(() => { // eslint-disable-next-line no-throw-literal throw null; - }).not[toThrow](expect.anything()); - }); + }).toThrow(expect.anything()), + ).toThrowErrorMatchingSnapshot(); + }); + + test('isNot true', () => { + expect(() => + jestExpect(() => { + throw new CustomError('apple'); + }).not.toThrow(expect.anything()), + ).toThrowErrorMatchingSnapshot(); + }); + }); + }); + + describe('no-symbol', () => { + // Test serialization of asymmetric matcher which has no property: + // this.$$typeof = Symbol.for('jest.asymmetricMatcher') + const matchError = { + asymmetricMatch(received: Error | null | undefined) { + return ( + received !== null && + received !== undefined && + received.name === 'Error' + ); + }, + }; + const matchNotError = { + asymmetricMatch(received: Error | null | undefined) { + return ( + received !== null && + received !== undefined && + received.name !== 'Error' + ); + }, + }; + + describe('pass', () => { + test('isNot false', () => { + jestExpect(() => { + throw new CustomError('apple'); + }).toThrow(matchError); }); - describe('fail', () => { - test('isNot false', () => { - expect(() => - jestExpect(() => { - // eslint-disable-next-line no-throw-literal - throw null; - })[toThrow](expect.anything()), - ).toThrowErrorMatchingSnapshot(); - }); - - test('isNot true', () => { - expect(() => - jestExpect(() => { - throw new CustomError('apple'); - }).not[toThrow](expect.anything()), - ).toThrowErrorMatchingSnapshot(); - }); + test('isNot true', () => { + jestExpect(() => { + throw new CustomError('apple'); + }).not.toThrow(matchNotError); }); }); - describe('no-symbol', () => { - // Test serialization of asymmetric matcher which has no property: - // this.$$typeof = Symbol.for('jest.asymmetricMatcher') - const matchError = { - asymmetricMatch(received: Error | null | undefined) { - return ( - received !== null && - received !== undefined && - received.name === 'Error' - ); - }, - }; - const matchNotError = { - asymmetricMatch(received: Error | null | undefined) { - return ( - received !== null && - received !== undefined && - received.name !== 'Error' - ); - }, - }; - - describe('pass', () => { - test('isNot false', () => { + describe('fail', () => { + test('isNot false', () => { + expect(() => jestExpect(() => { throw new CustomError('apple'); - })[toThrow](matchError); - }); + }).toThrow(matchNotError), + ).toThrowErrorMatchingSnapshot(); + }); - test('isNot true', () => { + test('isNot true', () => { + expect(() => jestExpect(() => { throw new CustomError('apple'); - }).not[toThrow](matchNotError); - }); + }).not.toThrow(matchError), + ).toThrowErrorMatchingSnapshot(); }); + }); + }); - describe('fail', () => { - test('isNot false', () => { - expect(() => - jestExpect(() => { - throw new CustomError('apple'); - })[toThrow](matchNotError), - ).toThrowErrorMatchingSnapshot(); - }); - - test('isNot true', () => { - expect(() => - jestExpect(() => { - throw new CustomError('apple'); - }).not[toThrow](matchError), - ).toThrowErrorMatchingSnapshot(); - }); - }); + describe('objectContaining', () => { + const matchError = expect.objectContaining({ + name: 'Error', + }); + const matchNotError = expect.objectContaining({ + name: 'NotError', }); - describe('objectContaining', () => { - const matchError = expect.objectContaining({ - name: 'Error', + describe('pass', () => { + test('isNot false', () => { + jestExpect(() => { + throw new CustomError('apple'); + }).toThrow(matchError); }); - const matchNotError = expect.objectContaining({ - name: 'NotError', + + test('isNot true', () => { + jestExpect(() => { + throw new CustomError('apple'); + }).not.toThrow(matchNotError); }); + }); - describe('pass', () => { - test('isNot false', () => { + describe('fail', () => { + test('isNot false', () => { + expect(() => jestExpect(() => { throw new CustomError('apple'); - })[toThrow](matchError); - }); + }).toThrow(matchNotError), + ).toThrowErrorMatchingSnapshot(); + }); - test('isNot true', () => { + test('isNot true', () => { + expect(() => jestExpect(() => { throw new CustomError('apple'); - }).not[toThrow](matchNotError); - }); - }); - - describe('fail', () => { - test('isNot false', () => { - expect(() => - jestExpect(() => { - throw new CustomError('apple'); - })[toThrow](matchNotError), - ).toThrowErrorMatchingSnapshot(); - }); - - test('isNot true', () => { - expect(() => - jestExpect(() => { - throw new CustomError('apple'); - }).not[toThrow](matchError), - ).toThrowErrorMatchingSnapshot(); - }); + }).not.toThrow(matchError), + ).toThrowErrorMatchingSnapshot(); }); }); }); + }); - describe('promise/async throws if Error-like object is returned', () => { - const asyncFn = async (shouldThrow?: boolean, resolve?: boolean) => { - let err; - if (shouldThrow) { - err = new Err('async apple'); - } - if (resolve) { - return await Promise.resolve(err || 'apple'); - } else { - return await Promise.reject(err || 'apple'); - } - }; - - test('passes', async () => { - expect.assertions(24); - await jestExpect(Promise.reject(new Error())).rejects[toThrow](); - - await jestExpect(asyncFn(true)).rejects[toThrow](); - await jestExpect(asyncFn(true)).rejects[toThrow](Err); - await jestExpect(asyncFn(true)).rejects[toThrow](Error); - await jestExpect(asyncFn(true)).rejects[toThrow]('apple'); - await jestExpect(asyncFn(true)).rejects[toThrow](/app/); - - await jestExpect(asyncFn(true)).rejects.not[toThrow](Err2); - await jestExpect(asyncFn(true)).rejects.not[toThrow]('banana'); - await jestExpect(asyncFn(true)).rejects.not[toThrow](/banana/); - - await jestExpect(asyncFn(true, true)).resolves[toThrow](); - - await jestExpect(asyncFn(false, true)).resolves.not[toThrow](); - await jestExpect(asyncFn(false, true)).resolves.not[toThrow](Error); - await jestExpect(asyncFn(false, true)).resolves.not[toThrow]('apple'); - await jestExpect(asyncFn(false, true)).resolves.not[toThrow](/apple/); - await jestExpect(asyncFn(false, true)).resolves.not[toThrow]('banana'); - await jestExpect(asyncFn(false, true)).resolves.not[toThrow](/banana/); - - await jestExpect(asyncFn()).rejects.not[toThrow](); - await jestExpect(asyncFn()).rejects.not[toThrow](Error); - await jestExpect(asyncFn()).rejects.not[toThrow]('apple'); - await jestExpect(asyncFn()).rejects.not[toThrow](/apple/); - await jestExpect(asyncFn()).rejects.not[toThrow]('banana'); - await jestExpect(asyncFn()).rejects.not[toThrow](/banana/); - - // Works with nested functions inside promises - await jestExpect( - Promise.reject(() => { - throw new Error(); - }), - ).rejects[toThrow](); - await jestExpect(Promise.reject(() => {})).rejects.not[toThrow](); - }); - - test('did not throw at all', async () => { - await expect( - jestExpect(asyncFn()).rejects[toThrow](), - ).rejects.toThrowErrorMatchingSnapshot(); - }); - - test('threw, but class did not match', async () => { - await expect( - jestExpect(asyncFn(true)).rejects[toThrow](Err2), - ).rejects.toThrowErrorMatchingSnapshot(); - }); + describe('promise/async throws if Error-like object is returned', () => { + const asyncFn = async (shouldThrow?: boolean, resolve?: boolean) => { + let err; + if (shouldThrow) { + err = new Err('async apple'); + } + if (resolve) { + return await Promise.resolve(err || 'apple'); + } else { + return await Promise.reject(err || 'apple'); + } + }; + + test('passes', async () => { + expect.assertions(24); + await jestExpect(Promise.reject(new Error())).rejects.toThrow(); + + await jestExpect(asyncFn(true)).rejects.toThrow(); + await jestExpect(asyncFn(true)).rejects.toThrow(Err); + await jestExpect(asyncFn(true)).rejects.toThrow(Error); + await jestExpect(asyncFn(true)).rejects.toThrow('apple'); + await jestExpect(asyncFn(true)).rejects.toThrow(/app/); + + await jestExpect(asyncFn(true)).rejects.not.toThrow(Err2); + await jestExpect(asyncFn(true)).rejects.not.toThrow('banana'); + await jestExpect(asyncFn(true)).rejects.not.toThrow(/banana/); + + await jestExpect(asyncFn(true, true)).resolves.toThrow(); + + await jestExpect(asyncFn(false, true)).resolves.not.toThrow(); + await jestExpect(asyncFn(false, true)).resolves.not.toThrow(Error); + await jestExpect(asyncFn(false, true)).resolves.not.toThrow('apple'); + await jestExpect(asyncFn(false, true)).resolves.not.toThrow(/apple/); + await jestExpect(asyncFn(false, true)).resolves.not.toThrow('banana'); + await jestExpect(asyncFn(false, true)).resolves.not.toThrow(/banana/); + + await jestExpect(asyncFn()).rejects.not.toThrow(); + await jestExpect(asyncFn()).rejects.not.toThrow(Error); + await jestExpect(asyncFn()).rejects.not.toThrow('apple'); + await jestExpect(asyncFn()).rejects.not.toThrow(/apple/); + await jestExpect(asyncFn()).rejects.not.toThrow('banana'); + await jestExpect(asyncFn()).rejects.not.toThrow(/banana/); + + // Works with nested functions inside promises + await jestExpect( + Promise.reject(() => { + throw new Error(); + }), + ).rejects.toThrow(); + await jestExpect(Promise.reject(() => {})).rejects.not.toThrow(); + }); - test('threw, but should not have', async () => { - await expect( - jestExpect(asyncFn(true)).rejects.not[toThrow](), - ).rejects.toThrowErrorMatchingSnapshot(); - }); + test('did not throw at all', async () => { + await expect( + jestExpect(asyncFn()).rejects.toThrow(), + ).rejects.toThrowErrorMatchingSnapshot(); }); - describe('expected is undefined', () => { - test('threw, but should not have (non-error falsey)', () => { - expect(() => { - jestExpect(() => { - // eslint-disable-next-line no-throw-literal - throw null; - }).not[toThrow](); - }).toThrowErrorMatchingSnapshot(); - }); + test('threw, but class did not match', async () => { + await expect( + jestExpect(asyncFn(true)).rejects.toThrow(Err2), + ).rejects.toThrowErrorMatchingSnapshot(); }); - test('invalid arguments', () => { - expect(() => - jestExpect(() => {}).not[toThrow](111), - ).toThrowErrorMatchingSnapshot(); + test('threw, but should not have', async () => { + await expect( + jestExpect(asyncFn(true)).rejects.not.toThrow(), + ).rejects.toThrowErrorMatchingSnapshot(); }); + }); - test('invalid actual', () => { - expect(() => - jestExpect('a string')[toThrow](), - ).toThrowErrorMatchingSnapshot(); + describe('expected is undefined', () => { + test('threw, but should not have (non-error falsey)', () => { + expect(() => { + jestExpect(() => { + // eslint-disable-next-line no-throw-literal + throw null; + }).not.toThrow(); + }).toThrowErrorMatchingSnapshot(); }); }); + + test('invalid arguments', () => { + expect(() => + jestExpect(() => {}).not.toThrow(111), + ).toThrowErrorMatchingSnapshot(); + }); + + test('invalid actual', () => { + expect(() => + jestExpect('a string').toThrow(), + ).toThrowErrorMatchingSnapshot(); + }); }); diff --git a/packages/expect/src/index.ts b/packages/expect/src/index.ts index 3172ec5de0f5..088ce0697e5f 100644 --- a/packages/expect/src/index.ts +++ b/packages/expect/src/index.ts @@ -87,7 +87,7 @@ const createToThrowErrorMatchingSnapshotMatcher = function ( }; const getPromiseMatcher = (name: string, matcher: RawMatcherFn) => { - if (name === 'toThrow' || name === 'toThrowError') { + if (name === 'toThrow') { return createThrowMatcher(name, true); } else if ( name === 'toThrowErrorMatchingSnapshot' || diff --git a/packages/expect/src/toThrowMatchers.ts b/packages/expect/src/toThrowMatchers.ts index fdd21d184d6b..c258dd753b8b 100644 --- a/packages/expect/src/toThrowMatchers.ts +++ b/packages/expect/src/toThrowMatchers.ts @@ -143,7 +143,6 @@ export const createMatcher = ( const matchers: MatchersObject = { toThrow: createMatcher('toThrow'), - toThrowError: createMatcher('toThrowError'), }; const toThrowExpectedRegExp = ( diff --git a/packages/expect/src/types.ts b/packages/expect/src/types.ts index 24c063f4022d..233022696956 100644 --- a/packages/expect/src/types.ts +++ b/packages/expect/src/types.ts @@ -334,8 +334,4 @@ export interface Matchers> { * Used to test that a function throws when it is called. */ toThrow(expected?: unknown): R; - /** - * If you want to test that a specific error is thrown inside a function. - */ - toThrowError(expected?: unknown): R; } diff --git a/packages/jest-circus/src/__tests__/circusItFailingTestError.test.ts b/packages/jest-circus/src/__tests__/circusItFailingTestError.test.ts index 65322ba71184..f374a47b8646 100644 --- a/packages/jest-circus/src/__tests__/circusItFailingTestError.test.ts +++ b/packages/jest-circus/src/__tests__/circusItFailingTestError.test.ts @@ -22,47 +22,47 @@ describe('test/it.failing error throwing', () => { it("it doesn't throw an error with valid arguments", () => { expect(() => { circusIt.failing('test1', () => {}); - }).not.toThrowError(); + }).not.toThrow(); }); it('it throws error with missing callback function', () => { expect(() => { circusIt.failing('test2'); - }).toThrowError( + }).toThrow( 'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.', ); }); it("it throws an error when first argument isn't valid", () => { expect(() => { circusIt.failing(() => {}); - }).toThrowError( + }).toThrow( 'Invalid first argument, () => {}. It must be a named class, named function, number, or string.', ); }); it('it throws an error when callback function is not a function', () => { expect(() => { circusIt.failing('test4', 'test4b'); - }).toThrowError( + }).toThrow( 'Invalid second argument, test4b. It must be a callback function.', ); }); it('test throws error with missing callback function', () => { expect(() => { circusTest.failing('test5'); - }).toThrowError( + }).toThrow( 'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.', ); }); it("test throws an error when first argument isn't a string", () => { expect(() => { circusTest.failing(() => {}); - }).toThrowError( + }).toThrow( 'Invalid first argument, () => {}. It must be a named class, named function, number, or string.', ); }); it('test throws an error when callback function is not a function', () => { expect(() => { circusTest.failing('test7', 'test8b'); - }).toThrowError( + }).toThrow( 'Invalid second argument, test8b. It must be a callback function.', ); }); diff --git a/packages/jest-circus/src/__tests__/circusItTestError.test.ts b/packages/jest-circus/src/__tests__/circusItTestError.test.ts index f4f7a03d3611..36b1972c093a 100644 --- a/packages/jest-circus/src/__tests__/circusItTestError.test.ts +++ b/packages/jest-circus/src/__tests__/circusItTestError.test.ts @@ -25,13 +25,13 @@ describe('test/it error throwing', () => { it("it doesn't throw an error with valid arguments", () => { expect(() => { circusIt('test1', () => {}); - }).not.toThrowError(); + }).not.toThrow(); }); it('it throws error with missing callback function', () => { expect(() => { // @ts-expect-error: Easy, we're testing runtime errors here circusIt('test2'); - }).toThrowError( + }).toThrow( 'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.', ); }); @@ -39,7 +39,7 @@ describe('test/it error throwing', () => { expect(() => { // @ts-expect-error: Easy, we're testing runtime errors here circusIt(() => {}); - }).toThrowError( + }).toThrow( 'Invalid first argument, () => {}. It must be a named class, named function, number, or string.', ); }); @@ -47,20 +47,20 @@ describe('test/it error throwing', () => { expect(() => { // @ts-expect-error: Easy, we're testing runtime errors here circusIt('test4', 'test4b'); - }).toThrowError( + }).toThrow( 'Invalid second argument, test4b. It must be a callback function.', ); }); it("test doesn't throw an error with valid arguments", () => { expect(() => { circusTest('test5', () => {}); - }).not.toThrowError(); + }).not.toThrow(); }); it('test throws error with missing callback function', () => { expect(() => { // @ts-expect-error: Easy, we're testing runtime errors here circusTest('test6'); - }).toThrowError( + }).toThrow( 'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.', ); }); @@ -68,7 +68,7 @@ describe('test/it error throwing', () => { expect(() => { // @ts-expect-error: Easy, we're testing runtime errors here circusTest(() => {}); - }).toThrowError( + }).toThrow( 'Invalid first argument, () => {}. It must be a named class, named function, number, or string.', ); }); @@ -76,7 +76,7 @@ describe('test/it error throwing', () => { expect(() => { // @ts-expect-error: Easy, we're testing runtime errors here circusTest('test8', 'test8b'); - }).toThrowError( + }).toThrow( 'Invalid second argument, test8b. It must be a callback function.', ); }); diff --git a/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts b/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts index b783b7b3069a..b5b9da7f000e 100644 --- a/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts +++ b/packages/jest-circus/src/__tests__/circusItTodoTestError.test.ts @@ -24,17 +24,17 @@ describe('test/it.todo error throwing', () => { expect(() => { // @ts-expect-error: Testing runtime errors here circusIt.todo(); - }).toThrowError('Todo must be called with only a description.'); + }).toThrow('Todo must be called with only a description.'); }); it('todo throws error when given more than one argument', () => { expect(() => { circusIt.todo('test1', () => {}); - }).toThrowError('Todo must be called with only a description.'); + }).toThrow('Todo must be called with only a description.'); }); it('todo throws error when given none string description', () => { expect(() => { // @ts-expect-error: Testing runtime errors here circusIt.todo(() => {}); - }).toThrowError('Todo must be called with only a description.'); + }).toThrow('Todo must be called with only a description.'); }); }); diff --git a/packages/jest-circus/src/__tests__/hooksError.test.ts b/packages/jest-circus/src/__tests__/hooksError.test.ts index 7781d7604123..77de352f7794 100644 --- a/packages/jest-circus/src/__tests__/hooksError.test.ts +++ b/packages/jest-circus/src/__tests__/hooksError.test.ts @@ -25,9 +25,7 @@ describe.each(['beforeEach', 'beforeAll', 'afterEach', 'afterAll'])( el => { expect(() => { circus[fn](el); - }).toThrowError( - 'Invalid first argument. It must be a callback function.', - ); + }).toThrow('Invalid first argument. It must be a callback function.'); }, ); }, diff --git a/packages/jest-config/src/__tests__/normalize.test.ts b/packages/jest-config/src/__tests__/normalize.test.ts index 8f2956fad502..fb791da3de31 100644 --- a/packages/jest-config/src/__tests__/normalize.test.ts +++ b/packages/jest-config/src/__tests__/normalize.test.ts @@ -1059,9 +1059,7 @@ describe('preset', () => { }, {} as Config.Argv, ), - ).rejects.toThrowError( - /Cannot find module 'library-that-is-not-installed'/, - ); + ).rejects.toThrow(/Cannot find module 'library-that-is-not-installed'/); }); test('throws when preset is invalid', async () => { @@ -1077,7 +1075,7 @@ describe('preset', () => { }, {} as Config.Argv, ), - ).rejects.toThrowError( + ).rejects.toThrow( /Unexpected token } in JSON at position (104|110)[\s\S]* at /, ); }); @@ -1103,7 +1101,7 @@ describe('preset', () => { }, {} as Config.Argv, ), - ).rejects.toThrowError(errorMessage); + ).rejects.toThrow(errorMessage); }); test('works with "react-native"', async () => { @@ -1699,7 +1697,7 @@ describe('moduleFileExtensions', () => { }, {} as Config.Argv, ), - ).rejects.toThrowError("moduleFileExtensions must include 'js'"); + ).rejects.toThrow("moduleFileExtensions must include 'js'"); }, ); diff --git a/packages/jest-config/src/__tests__/readConfig.test.ts b/packages/jest-config/src/__tests__/readConfig.test.ts index 1452e8355171..d00260fe411f 100644 --- a/packages/jest-config/src/__tests__/readConfig.test.ts +++ b/packages/jest-config/src/__tests__/readConfig.test.ts @@ -16,7 +16,7 @@ test('readConfig() throws when an object is passed without a file path', async ( false /* skipArgvConfigOption */, null /* parentConfigPath */, ), - ).rejects.toThrowError( + ).rejects.toThrow( 'Jest: Cannot use configuration as an object without a file path', ); }); diff --git a/packages/jest-config/src/__tests__/readConfigs.test.ts b/packages/jest-config/src/__tests__/readConfigs.test.ts index bdd76850552a..5da341118a3a 100644 --- a/packages/jest-config/src/__tests__/readConfigs.test.ts +++ b/packages/jest-config/src/__tests__/readConfigs.test.ts @@ -18,5 +18,5 @@ test('readConfigs() throws when called without project paths', async () => { await expect( // @ts-expect-error readConfigs(null /* argv */, [] /* projectPaths */), - ).rejects.toThrowError('jest: No configuration found for any project.'); + ).rejects.toThrow('jest: No configuration found for any project.'); }); diff --git a/packages/jest-config/src/__tests__/resolveConfigPath.test.ts b/packages/jest-config/src/__tests__/resolveConfigPath.test.ts index 167ab607bb31..515db568e6e9 100644 --- a/packages/jest-config/src/__tests__/resolveConfigPath.test.ts +++ b/packages/jest-config/src/__tests__/resolveConfigPath.test.ts @@ -32,7 +32,7 @@ describe.each(JEST_CONFIG_EXT_ORDER.slice(0))( expect(resolveConfigPath(absoluteConfigPath, DIR)).toBe( absoluteConfigPath, ); - expect(() => resolveConfigPath('/does_not_exist', DIR)).toThrowError( + expect(() => resolveConfigPath('/does_not_exist', DIR)).toThrow( NO_ROOT_DIR_ERROR_PATTERN, ); @@ -40,7 +40,7 @@ describe.each(JEST_CONFIG_EXT_ORDER.slice(0))( expect(resolveConfigPath(relativeConfigPath, DIR)).toBe( absoluteConfigPath, ); - expect(() => resolveConfigPath('does_not_exist', DIR)).toThrowError( + expect(() => resolveConfigPath('does_not_exist', DIR)).toThrow( NO_ROOT_DIR_ERROR_PATTERN, ); }); @@ -60,12 +60,12 @@ describe.each(JEST_CONFIG_EXT_ORDER.slice(0))( expect(() => // absolute resolveConfigPath(path.dirname(absoluteJestConfigPath), DIR), - ).toThrowError(ERROR_PATTERN); + ).toThrow(ERROR_PATTERN); expect(() => // relative resolveConfigPath(path.dirname(relativeJestConfigPath), DIR), - ).toThrowError(ERROR_PATTERN); + ).toThrow(ERROR_PATTERN); writeFiles(DIR, {[relativePackageJsonPath]: ''}); @@ -98,19 +98,19 @@ describe.each(JEST_CONFIG_EXT_ORDER.slice(0))( // absolute expect(() => resolveConfigPath(path.dirname(absolutePackageJsonPath), DIR), - ).toThrowError(MULTIPLE_CONFIGS_ERROR_PATTERN); + ).toThrow(MULTIPLE_CONFIGS_ERROR_PATTERN); // relative expect(() => resolveConfigPath(path.dirname(relativePackageJsonPath), DIR), - ).toThrowError(MULTIPLE_CONFIGS_ERROR_PATTERN); + ).toThrow(MULTIPLE_CONFIGS_ERROR_PATTERN); expect(() => { resolveConfigPath( path.join(path.dirname(relativePackageJsonPath), 'j/x/b/m/'), DIR, ); - }).toThrowError(NO_ROOT_DIR_ERROR_PATTERN); + }).toThrow(NO_ROOT_DIR_ERROR_PATTERN); }); }, ); @@ -146,7 +146,7 @@ describe.each(pickPairsWithSameOrder(JEST_CONFIG_EXT_ORDER))( expect(() => resolveConfigPath(path.dirname(relativeJestConfigPaths[0]), DIR), - ).toThrowError(MULTIPLE_CONFIGS_ERROR_PATTERN); + ).toThrow(MULTIPLE_CONFIGS_ERROR_PATTERN); }); }, ); diff --git a/packages/jest-config/src/__tests__/stringToBytes.test.ts b/packages/jest-config/src/__tests__/stringToBytes.test.ts index 7c5902ec1acb..7baaba6798d7 100644 --- a/packages/jest-config/src/__tests__/stringToBytes.test.ts +++ b/packages/jest-config/src/__tests__/stringToBytes.test.ts @@ -21,11 +21,11 @@ describe('numeric input', () => { }); test('should throw when no reference supplied', () => { - expect(() => stringToBytes(0.3)).toThrowError(); + expect(() => stringToBytes(0.3)).toThrow(); }); test('should throw on a bad input', () => { - expect(() => stringToBytes(-0.3, 51)).toThrowError(); + expect(() => stringToBytes(-0.3, 51)).toThrow(); }); }); @@ -40,17 +40,17 @@ describe('string input', () => { }); test('should throw when no reference supplied', () => { - expect(() => stringToBytes('0.3')).toThrowError(); + expect(() => stringToBytes('0.3')).toThrow(); }); test('should throw on a bad input', () => { - expect(() => stringToBytes('-0.3', 51)).toThrowError(); + expect(() => stringToBytes('-0.3', 51)).toThrow(); }); }); describe('parsing', () => { test('0% should throw an error', () => { - expect(() => stringToBytes('0%', 51)).toThrowError(); + expect(() => stringToBytes('0%', 51)).toThrow(); }); test('30%', () => { @@ -109,7 +109,7 @@ describe('string input', () => { }); test('unknown unit', () => { - expect(() => stringToBytes('50XX')).toThrowError(); + expect(() => stringToBytes('50XX')).toThrow(); }); }); }); diff --git a/packages/jest-core/src/__tests__/watch.test.js b/packages/jest-core/src/__tests__/watch.test.js index ef85c3fe1d13..ed52b2d72f5e 100644 --- a/packages/jest-core/src/__tests__/watch.test.js +++ b/packages/jest-core/src/__tests__/watch.test.js @@ -416,7 +416,7 @@ describe('Watch mode flows', () => { hasteMapInstances, stdin, ), - ).rejects.toThrowError( + ).rejects.toThrow( new RegExp( `Watch plugin OffendingWatchPlugin attempted to register key <${key}>,\\s+that is reserved internally for .+\\.\\s+Please change the configuration key for this plugin\\.`, 'm', @@ -505,7 +505,7 @@ describe('Watch mode flows', () => { hasteMapInstances, stdin, ), - ).rejects.toThrowError( + ).rejects.toThrow( /Watch plugins OffendingFooThirdPartyWatchPlugin and OffendingBarThirdPartyWatchPlugin both attempted to register key \.\s+Please change the key configuration for one of the conflicting plugins to avoid overlap\./m, ); }); diff --git a/packages/jest-each/src/__tests__/template.test.ts b/packages/jest-each/src/__tests__/template.test.ts index f39031840f93..fce4add2dedc 100644 --- a/packages/jest-each/src/__tests__/template.test.ts +++ b/packages/jest-each/src/__tests__/template.test.ts @@ -82,7 +82,7 @@ describe('jest-each', () => { const globalMock = get(globalTestMocks, keyPath); - expect(() => globalMock.mock.calls[0][1]()).not.toThrowError(); + expect(() => globalMock.mock.calls[0][1]()).not.toThrow(); expect(testCallBack).toHaveBeenCalledWith({ b: 1, expected: 2, @@ -120,7 +120,7 @@ describe('jest-each', () => { const globalMock = get(globalTestMocks, keyPath); - expect(() => globalMock.mock.calls[0][1]()).not.toThrowError(); + expect(() => globalMock.mock.calls[0][1]()).not.toThrow(); expect(testCallBack).toHaveBeenCalledWith({ a: 1, expected: 2, @@ -158,7 +158,7 @@ describe('jest-each', () => { const globalMock = get(globalTestMocks, keyPath); - expect(() => globalMock.mock.calls[0][1]()).not.toThrowError(); + expect(() => globalMock.mock.calls[0][1]()).not.toThrow(); expect(testCallBack).toHaveBeenCalledWith({ '(๑ఠ‿ఠ๑)<expected': 2, a: 1, diff --git a/packages/jest-globals/src/__tests__/index.ts b/packages/jest-globals/src/__tests__/index.ts index cb0af7398581..3cd8f7797b06 100644 --- a/packages/jest-globals/src/__tests__/index.ts +++ b/packages/jest-globals/src/__tests__/index.ts @@ -6,7 +6,7 @@ */ test('throw when directly imported', () => { - expect(() => require('../')).toThrowError( + expect(() => require('../')).toThrow( 'Do not import `@jest/globals` outside of the Jest test environment', ); }); diff --git a/packages/jest-jasmine2/src/__tests__/hooksError.test.ts b/packages/jest-jasmine2/src/__tests__/hooksError.test.ts index 13b80219ceeb..432f1f5c6bc3 100644 --- a/packages/jest-jasmine2/src/__tests__/hooksError.test.ts +++ b/packages/jest-jasmine2/src/__tests__/hooksError.test.ts @@ -25,9 +25,7 @@ describe.each([['beforeEach'], ['beforeAll'], ['afterEach'], ['afterAll']])( el => { expect(() => { globalThis[fn](el); - }).toThrowError( - 'Invalid first argument. It must be a callback function.', - ); + }).toThrow('Invalid first argument. It must be a callback function.'); }, ); }, diff --git a/packages/jest-jasmine2/src/__tests__/itTestError.test.ts b/packages/jest-jasmine2/src/__tests__/itTestError.test.ts index 24ad11cea344..c64275e72011 100644 --- a/packages/jest-jasmine2/src/__tests__/itTestError.test.ts +++ b/packages/jest-jasmine2/src/__tests__/itTestError.test.ts @@ -10,7 +10,7 @@ describe('test/it error throwing', () => { it('it throws error with missing callback function', () => { expect(() => { it('test1'); - }).toThrowError( + }).toThrow( 'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.', ); }); @@ -18,7 +18,7 @@ describe('test/it error throwing', () => { expect(() => { // @ts-expect-error it(() => {}); - }).toThrowError( + }).toThrow( 'Invalid first argument, () => {}. It must be a named class, named function, number, or string.', ); }); @@ -26,14 +26,14 @@ describe('test/it error throwing', () => { expect(() => { // @ts-expect-error it('test3', 'test3b'); - }).toThrowError( + }).toThrow( 'Invalid second argument, test3b. It must be a callback function.', ); }); test('test throws error with missing callback function', () => { expect(() => { test('test4'); - }).toThrowError( + }).toThrow( 'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.', ); }); @@ -41,7 +41,7 @@ describe('test/it error throwing', () => { expect(() => { // @ts-expect-error test(() => {}); - }).toThrowError( + }).toThrow( 'Invalid first argument, () => {}. It must be a named class, named function, number, or string.', ); }); @@ -49,7 +49,7 @@ describe('test/it error throwing', () => { expect(() => { // @ts-expect-error test('test6', 'test6b'); - }).toThrowError( + }).toThrow( 'Invalid second argument, test6b. It must be a callback function.', ); }); diff --git a/packages/jest-jasmine2/src/__tests__/todoError.test.ts b/packages/jest-jasmine2/src/__tests__/todoError.test.ts index aab30f522aca..a96523f1e6b5 100644 --- a/packages/jest-jasmine2/src/__tests__/todoError.test.ts +++ b/packages/jest-jasmine2/src/__tests__/todoError.test.ts @@ -11,17 +11,17 @@ describe('test/it.todo error throwing', () => { expect(() => { // @ts-expect-error it.todo(); - }).toThrowError('Todo must be called with only a description.'); + }).toThrow('Todo must be called with only a description.'); }); it('it throws error when given more than one argument', () => { expect(() => { it.todo('test1', () => {}); - }).toThrowError('Todo must be called with only a description.'); + }).toThrow('Todo must be called with only a description.'); }); it('it throws error when given none string description', () => { expect(() => { // @ts-expect-error it.todo(() => {}); - }).toThrowError('Todo must be called with only a description.'); + }).toThrow('Todo must be called with only a description.'); }); }); diff --git a/packages/jest-runtime/src/__tests__/runtime_require_module.test.js b/packages/jest-runtime/src/__tests__/runtime_require_module.test.js index eebec980006f..e0df323966b0 100644 --- a/packages/jest-runtime/src/__tests__/runtime_require_module.test.js +++ b/packages/jest-runtime/src/__tests__/runtime_require_module.test.js @@ -366,10 +366,10 @@ describe('Runtime requireModule', () => { const runtime = await createRuntime(__filename); expect(() => runtime.requireModule(runtime.__mockRootPath, 'throwing'), - ).toThrowError(); + ).toThrow(); expect(() => runtime.requireModule(runtime.__mockRootPath, 'throwing'), - ).toThrowError(); + ).toThrow(); }); it('overrides module.createRequire', async () => { diff --git a/packages/jest-runtime/src/__tests__/runtime_require_module_or_mock.test.js b/packages/jest-runtime/src/__tests__/runtime_require_module_or_mock.test.js index 3eaae70ec7e6..967453b55f53 100644 --- a/packages/jest-runtime/src/__tests__/runtime_require_module_or_mock.test.js +++ b/packages/jest-runtime/src/__tests__/runtime_require_module_or_mock.test.js @@ -187,7 +187,7 @@ it('unmocks virtual mocks after they have been mocked previously', async () => { expect(() => { runtime.requireModuleOrMock(runtime.__mockRootPath, 'my-virtual-module'); - }).toThrowError( + }).toThrow( new Error("Cannot find module 'my-virtual-module' from 'root.js'"), ); }); @@ -271,7 +271,7 @@ describe('isolateModules', () => { runtime.isolateModules(() => { throw new Error('Error from isolated module'); }), - ).toThrowError('Error from isolated module'); + ).toThrow('Error from isolated module'); runtime.isolateModules(() => { expect(true).toBe(true); @@ -286,7 +286,7 @@ describe('isolateModules', () => { runtime.isolateModules(() => { runtime.isolateModules(() => {}); }); - }).toThrowError( + }).toThrow( 'isolateModules cannot be nested inside another isolateModules.', ); }); diff --git a/packages/jest-snapshot/src/__tests__/InlineSnapshots.test.ts b/packages/jest-snapshot/src/__tests__/InlineSnapshots.test.ts index 74303a23a20e..4722fe3f29ff 100644 --- a/packages/jest-snapshot/src/__tests__/InlineSnapshots.test.ts +++ b/packages/jest-snapshot/src/__tests__/InlineSnapshots.test.ts @@ -359,7 +359,7 @@ test('saveInlineSnapshots() throws if frame does not match', () => { 'prettier', ); - expect(save).toThrowError(/Couldn't locate all inline snapshots./); + expect(save).toThrow(/Couldn't locate all inline snapshots./); }); test('saveInlineSnapshots() throws if multiple calls to to the same location', () => { @@ -377,7 +377,7 @@ test('saveInlineSnapshots() throws if multiple calls to to the same location', ( 'prettier', ); - expect(save).toThrowError( + expect(save).toThrow( /Multiple inline snapshots for the same call are not supported./, ); }); diff --git a/packages/jest-snapshot/src/__tests__/utils.test.ts b/packages/jest-snapshot/src/__tests__/utils.test.ts index 3f918a3cbeba..853db21e4172 100644 --- a/packages/jest-snapshot/src/__tests__/utils.test.ts +++ b/packages/jest-snapshot/src/__tests__/utils.test.ts @@ -32,7 +32,7 @@ import { test('keyToTestName()', () => { expect(keyToTestName('abc cde 12')).toBe('abc cde'); expect(keyToTestName('abc cde 12')).toBe('abc cde '); - expect(() => keyToTestName('abc cde')).toThrowError( + expect(() => keyToTestName('abc cde')).toThrow( 'Snapshot keys must end with a number.', ); }); @@ -77,7 +77,7 @@ test('getSnapshotData() throws when no snapshot version', () => { .mockImplementation(() => 'exports[`myKey`] = `
\n
`;\n'); const update = 'none'; - expect(() => getSnapshotData(filename, update)).toThrowError( + expect(() => getSnapshotData(filename, update)).toThrow( chalk.red( `${chalk.bold('Outdated snapshot')}: No snapshot header found. ` + 'Jest 19 introduced versioned snapshots to ensure all developers on ' + @@ -98,7 +98,7 @@ test('getSnapshotData() throws for older snapshot version', () => { ); const update = 'none'; - expect(() => getSnapshotData(filename, update)).toThrowError( + expect(() => getSnapshotData(filename, update)).toThrow( `${chalk.red( `${chalk.red.bold('Outdated snapshot')}: The version of the snapshot ` + 'file associated with this test is outdated. The snapshot file ' + @@ -121,7 +121,7 @@ test('getSnapshotData() throws for newer snapshot version', () => { ); const update = 'none'; - expect(() => getSnapshotData(filename, update)).toThrowError( + expect(() => getSnapshotData(filename, update)).toThrow( `${chalk.red( `${chalk.red.bold('Outdated Jest version')}: The version of this ` + 'snapshot file indicates that this project is meant to be used ' + diff --git a/packages/jest-types/__typetests__/expect.test.ts b/packages/jest-types/__typetests__/expect.test.ts index 945dbd380451..4fe753a83372 100644 --- a/packages/jest-types/__typetests__/expect.test.ts +++ b/packages/jest-types/__typetests__/expect.test.ts @@ -191,12 +191,6 @@ expectType(expect(() => {}).toThrow('error')); expectType(expect(() => {}).toThrow(Error)); expectType(expect(() => {}).toThrow(new Error('error'))); -expectType(expect(() => {}).toThrowError()); -expectType(expect(() => {}).toThrowError(/error/)); -expectType(expect(() => {}).toThrowError('error')); -expectType(expect(() => {}).toThrowError(Error)); -expectType(expect(() => {}).toThrowError(new Error('error'))); - // mock matchers expectType(expect(jest.fn()).toBeCalled()); diff --git a/packages/jest-util/src/__tests__/convertDescriptorToString.test.ts b/packages/jest-util/src/__tests__/convertDescriptorToString.test.ts index 5aba082873a2..9c846fd60eca 100644 --- a/packages/jest-util/src/__tests__/convertDescriptorToString.test.ts +++ b/packages/jest-util/src/__tests__/convertDescriptorToString.test.ts @@ -29,7 +29,7 @@ describe(convertDescriptorToString, () => { expect(() => { // @ts-expect-error return convertDescriptorToString(input); - }).toThrowError( + }).toThrow( `Invalid first argument, ${input}. It must be a named class, named function, number, or string.`, ); }); diff --git a/packages/jest-worker/src/workers/__tests__/WorkerEdgeCases.test.js b/packages/jest-worker/src/workers/__tests__/WorkerEdgeCases.test.js index 0b68ea8755a6..59127f30c9c1 100644 --- a/packages/jest-worker/src/workers/__tests__/WorkerEdgeCases.test.js +++ b/packages/jest-worker/src/workers/__tests__/WorkerEdgeCases.test.js @@ -54,7 +54,7 @@ afterAll(async () => { test.each(filesToBuild)('%s.js should exist', async file => { const path = join(writeDestination, `${file}.js`); - await expect(async () => await access(path)).not.toThrowError(); + await expect(async () => await access(path)).not.toThrow(); }); async function closeWorkerAfter(worker, testBody) { @@ -317,7 +317,7 @@ describe.each([ test('worker stays dead', async () => { await expect( async () => await worker.waitForWorkerReady(), - ).rejects.toThrowError(); + ).rejects.toThrow(); expect(worker.isWorkerRunning()).toBeFalsy(); }); @@ -385,7 +385,7 @@ describe.each([ test('processes exits', async () => { worker.forceExit(); - await expect(() => worker.waitForWorkerReady()).rejects.toThrowError(); + await expect(() => worker.waitForWorkerReady()).rejects.toThrow(); }); }); }); From a3e4db979ef55b10b69b38954e9b3d2711b10b44 Mon Sep 17 00:00:00 2001 From: EduardoSCosta Date: Mon, 29 Aug 2022 16:29:10 -0300 Subject: [PATCH 02/13] chore: remove .toBeCalled() matcher --- .../__tests__/storage/track/Track.test.js | 2 +- .../storage/track/TrackExpected.test.js | 2 +- .../jquery/__tests__/display_user.test.js | 2 +- .../__tests__/infinite_timer_game.test.js | 2 +- examples/timer/__tests__/timer_game.test.js | 8 +- .../__snapshots__/spyMatchers.test.ts.snap | 52 ------------ .../expect/src/__tests__/spyMatchers.test.ts | 82 ++++++++++--------- packages/expect/src/spyMatchers.ts | 1 - packages/expect/src/types.ts | 4 - .../src/__tests__/TestScheduler.test.js | 2 +- .../jest-core/src/__tests__/watch.test.js | 4 +- .../watchFilenamePatternMode.test.js | 2 +- .../watchTestNamePatternMode.test.js | 2 +- .../src/__tests__/legacyFakeTimers.test.ts | 2 +- .../src/__tests__/modernFakeTimers.test.ts | 2 +- .../src/__tests__/index.test.js | 10 +-- .../src/crawlers/__tests__/watchman.test.js | 8 +- .../src/__tests__/runtime_jest_fn.js | 12 +-- .../src/__tests__/ScriptTransformer.test.ts | 48 ++++++----- .../jest-types/__typetests__/expect.test.ts | 4 +- .../src/__tests__/deepCyclicCopy.test.ts | 2 +- .../src/__tests__/validate.test.ts | 8 +- .../src/__tests__/WorkerPool.test.js | 6 +- .../src/__tests__/prettyFormat.test.ts | 4 +- 24 files changed, 113 insertions(+), 158 deletions(-) diff --git a/e2e/module-name-mapper-mock/__tests__/storage/track/Track.test.js b/e2e/module-name-mapper-mock/__tests__/storage/track/Track.test.js index 2a1737478788..be6c16f0c18f 100644 --- a/e2e/module-name-mapper-mock/__tests__/storage/track/Track.test.js +++ b/e2e/module-name-mapper-mock/__tests__/storage/track/Track.test.js @@ -10,5 +10,5 @@ jest.mock('@@storage/track/Track'); test('relative import', () => { const track = new Track(); - expect(track.someRandomFunction).not.toBeCalled(); + expect(track.someRandomFunction).not.toHaveBeenCalled(); }); diff --git a/e2e/module-name-mapper-mock/__tests__/storage/track/TrackExpected.test.js b/e2e/module-name-mapper-mock/__tests__/storage/track/TrackExpected.test.js index 86224f67fe7d..494d7056bdce 100644 --- a/e2e/module-name-mapper-mock/__tests__/storage/track/TrackExpected.test.js +++ b/e2e/module-name-mapper-mock/__tests__/storage/track/TrackExpected.test.js @@ -10,5 +10,5 @@ jest.mock('@@storage/track/Track'); test('through moduleNameMapper', () => { const track = new Track(); - expect(track.someRandomFunction).not.toBeCalled(); + expect(track.someRandomFunction).not.toHaveBeenCalled(); }); diff --git a/examples/jquery/__tests__/display_user.test.js b/examples/jquery/__tests__/display_user.test.js index 09d7b655b19f..54f540abd853 100644 --- a/examples/jquery/__tests__/display_user.test.js +++ b/examples/jquery/__tests__/display_user.test.js @@ -34,6 +34,6 @@ it('displays a user after a click', () => { // Assert that the fetchCurrentUser function was called, and that the // #username span's inner text was updated as we'd expect it to. - expect(fetchCurrentUser).toBeCalled(); + expect(fetchCurrentUser).toHaveBeenCalled(); expect($('#username').text()).toEqual('Johnny Cash - Logged In'); }); diff --git a/examples/timer/__tests__/infinite_timer_game.test.js b/examples/timer/__tests__/infinite_timer_game.test.js index 9266ded414e2..c2f8e8e98041 100644 --- a/examples/timer/__tests__/infinite_timer_game.test.js +++ b/examples/timer/__tests__/infinite_timer_game.test.js @@ -21,7 +21,7 @@ it('schedules a 10-second timer after 1 second', () => { jest.runOnlyPendingTimers(); // At this point, our 1-second timer should have fired its callback - expect(callback).toBeCalled(); + expect(callback).toHaveBeenCalled(); // And it should have created a new timer to start the game over in // 10 seconds diff --git a/examples/timer/__tests__/timer_game.test.js b/examples/timer/__tests__/timer_game.test.js index f7f94304f2e3..70df7fb37d3e 100644 --- a/examples/timer/__tests__/timer_game.test.js +++ b/examples/timer/__tests__/timer_game.test.js @@ -23,13 +23,13 @@ describe('timerGame', () => { timerGame(callback); // At this point in time, the callback should not have been called yet - expect(callback).not.toBeCalled(); + expect(callback).not.toHaveBeenCalled(); // Fast-forward until all timers have been executed jest.runAllTimers(); // Now our callback should have been called! - expect(callback).toBeCalled(); + expect(callback).toHaveBeenCalled(); expect(callback).toBeCalledTimes(1); }); @@ -40,13 +40,13 @@ describe('timerGame', () => { timerGame(callback); // At this point in time, the callback should not have been called yet - expect(callback).not.toBeCalled(); + expect(callback).not.toHaveBeenCalled(); // Fast-forward until all timers have been executed jest.advanceTimersByTime(1000); // Now our callback should have been called! - expect(callback).toBeCalled(); + expect(callback).toHaveBeenCalled(); expect(callback).toBeCalledTimes(1); }); }); diff --git a/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap b/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap index af10f62cd39a..ac363e888745 100644 --- a/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap +++ b/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap @@ -819,58 +819,6 @@ Expected: not undefined Number of returns: 1 `; -exports[`toBeCalled .not fails with any argument passed 1`] = ` -expect(received).not.toBeCalled() - -Matcher error: this matcher must not have an expected argument - -Expected has type: number -Expected has value: 555 -`; - -exports[`toBeCalled .not passes when called 1`] = ` -expect(spy).toBeCalled() - -Expected number of calls: >= 1 -Received number of calls: 0 -`; - -exports[`toBeCalled fails with any argument passed 1`] = ` -expect(received).toBeCalled() - -Matcher error: this matcher must not have an expected argument - -Expected has type: number -Expected has value: 555 -`; - -exports[`toBeCalled includes the custom mock name in the error message 1`] = ` -expect(named-mock).not.toBeCalled() - -Expected number of calls: 0 -Received number of calls: 1 - -1: called with 0 arguments -`; - -exports[`toBeCalled passes when called 1`] = ` -expect(jest.fn()).not.toBeCalled() - -Expected number of calls: 0 -Received number of calls: 1 - -1: "arg0", "arg1", "arg2" -`; - -exports[`toBeCalled works only on spies or jest.fn 1`] = ` -expect(received).toBeCalled() - -Matcher error: received value must be a mock or spy function - -Received has type: function -Received has value: [Function fn] -`; - exports[`toBeCalledTimes .not only accepts a number argument 1`] = ` expect(received).not.toBeCalledTimes(expected) diff --git a/packages/expect/src/__tests__/spyMatchers.test.ts b/packages/expect/src/__tests__/spyMatchers.test.ts index 48dc65edcc3e..93b8b6fd0757 100644 --- a/packages/expect/src/__tests__/spyMatchers.test.ts +++ b/packages/expect/src/__tests__/spyMatchers.test.ts @@ -34,53 +34,61 @@ const createSpy = (fn: jest.Mock) => { return spy; }; -['toBeCalled', 'toHaveBeenCalled'].forEach(called => { - describe(`${called}`, () => { - test('works only on spies or jest.fn', () => { - const fn = function fn() {}; +describe('toHaveBeenCalled', () => { + test('works only on spies or jest.fn', () => { + const fn = function fn() {}; - expect(() => jestExpect(fn)[called]()).toThrowErrorMatchingSnapshot(); - }); + expect(() => + jestExpect(fn).toHaveBeenCalled(), + ).toThrowErrorMatchingSnapshot(); + }); - test('passes when called', () => { - const fn = jest.fn(); - fn('arg0', 'arg1', 'arg2'); - jestExpect(createSpy(fn))[called](); - jestExpect(fn)[called](); - expect(() => jestExpect(fn).not[called]()).toThrowErrorMatchingSnapshot(); - }); + test('passes when called', () => { + const fn = jest.fn(); + fn('arg0', 'arg1', 'arg2'); + jestExpect(createSpy(fn)).toHaveBeenCalled(); + jestExpect(fn).toHaveBeenCalled(); + expect(() => + jestExpect(fn).not.toHaveBeenCalled(), + ).toThrowErrorMatchingSnapshot(); + }); - test('.not passes when called', () => { - const fn = jest.fn(); - const spy = createSpy(fn); + test('.not passes when called', () => { + const fn = jest.fn(); + const spy = createSpy(fn); - jestExpect(spy).not[called](); - jestExpect(fn).not[called](); - expect(() => jestExpect(spy)[called]()).toThrowErrorMatchingSnapshot(); - }); + jestExpect(spy).not.toHaveBeenCalled(); + jestExpect(fn).not.toHaveBeenCalled(); + expect(() => + jestExpect(spy).toHaveBeenCalled(), + ).toThrowErrorMatchingSnapshot(); + }); - test('fails with any argument passed', () => { - const fn = jest.fn(); + test('fails with any argument passed', () => { + const fn = jest.fn(); - fn(); - expect(() => jestExpect(fn)[called](555)).toThrowErrorMatchingSnapshot(); - }); + fn(); + expect(() => + jestExpect(fn).toHaveBeenCalled(555), + ).toThrowErrorMatchingSnapshot(); + }); - test('.not fails with any argument passed', () => { - const fn = jest.fn(); + test('.not fails with any argument passed', () => { + const fn = jest.fn(); - expect(() => - jestExpect(fn).not[called](555), - ).toThrowErrorMatchingSnapshot(); - }); + expect(() => + jestExpect(fn).not.toHaveBeenCalled(555), + ).toThrowErrorMatchingSnapshot(); + }); - test('includes the custom mock name in the error message', () => { - const fn = jest.fn().mockName('named-mock'); + test('includes the custom mock name in the error message', () => { + const fn = jest.fn().mockName('named-mock'); - fn(); - jestExpect(fn)[called](); - expect(() => jestExpect(fn).not[called]()).toThrowErrorMatchingSnapshot(); - }); + fn(); + jestExpect(fn).toHaveBeenCalled(); + expect(() => + jestExpect(fn).not.toHaveBeenCalled(), + ).toThrowErrorMatchingSnapshot(); }); }); diff --git a/packages/expect/src/spyMatchers.ts b/packages/expect/src/spyMatchers.ts index 7298545d3101..c8ea6bf188a4 100644 --- a/packages/expect/src/spyMatchers.ts +++ b/packages/expect/src/spyMatchers.ts @@ -1140,7 +1140,6 @@ const spyMatchers: MatchersObject = { lastReturnedWith: createLastReturnedMatcher('lastReturnedWith'), nthCalledWith: createNthCalledWithMatcher('nthCalledWith'), nthReturnedWith: createNthReturnedWithMatcher('nthReturnedWith'), - toBeCalled: createToBeCalledMatcher('toBeCalled'), toBeCalledTimes: createToBeCalledTimesMatcher('toBeCalledTimes'), toBeCalledWith: createToBeCalledWithMatcher('toBeCalledWith'), toHaveBeenCalled: createToBeCalledMatcher('toHaveBeenCalled'), diff --git a/packages/expect/src/types.ts b/packages/expect/src/types.ts index 233022696956..d8d902e8db64 100644 --- a/packages/expect/src/types.ts +++ b/packages/expect/src/types.ts @@ -153,10 +153,6 @@ export interface Matchers> { * Don't use `toBe` with floating-point numbers. */ toBe(expected: unknown): R; - /** - * Ensures that a mock function is called. - */ - toBeCalled(): R; /** * Ensures that a mock function is called an exact number of times. */ diff --git a/packages/jest-core/src/__tests__/TestScheduler.test.js b/packages/jest-core/src/__tests__/TestScheduler.test.js index 66aba2262bb0..69f98cb2c6f0 100644 --- a/packages/jest-core/src/__tests__/TestScheduler.test.js +++ b/packages/jest-core/src/__tests__/TestScheduler.test.js @@ -348,7 +348,7 @@ test('should not bail if less than `n` failures', async () => { snapshot: {}, testResults: [{}], }); - expect(setState).not.toBeCalled(); + expect(setState).not.toHaveBeenCalled(); }); test('should set runInBand to run in serial', async () => { diff --git a/packages/jest-core/src/__tests__/watch.test.js b/packages/jest-core/src/__tests__/watch.test.js index ed52b2d72f5e..5e82da8e1dff 100644 --- a/packages/jest-core/src/__tests__/watch.test.js +++ b/packages/jest-core/src/__tests__/watch.test.js @@ -816,7 +816,7 @@ describe('Watch mode flows', () => { stdin.emit('o'); - expect(runJestMock).toBeCalled(); + expect(runJestMock).toHaveBeenCalled(); expect(runJestMock.mock.calls[0][0].globalConfig).toMatchObject({ onlyChanged: true, watch: true, @@ -830,7 +830,7 @@ describe('Watch mode flows', () => { stdin.emit('a'); - expect(runJestMock).toBeCalled(); + expect(runJestMock).toHaveBeenCalled(); expect(runJestMock.mock.calls[0][0].globalConfig).toMatchObject({ onlyChanged: false, watch: false, diff --git a/packages/jest-core/src/__tests__/watchFilenamePatternMode.test.js b/packages/jest-core/src/__tests__/watchFilenamePatternMode.test.js index cde9694f668e..b9cf687d393c 100644 --- a/packages/jest-core/src/__tests__/watchFilenamePatternMode.test.js +++ b/packages/jest-core/src/__tests__/watchFilenamePatternMode.test.js @@ -111,7 +111,7 @@ describe('Watch mode flows', () => { // Runs Jest again runJestMock.mockReset(); stdin.emit(KEYS.ENTER); - expect(runJestMock).toBeCalled(); + expect(runJestMock).toHaveBeenCalled(); // globalConfig is updated with the current pattern expect(runJestMock.mock.calls[0][0].globalConfig).toMatchSnapshot(); diff --git a/packages/jest-core/src/__tests__/watchTestNamePatternMode.test.js b/packages/jest-core/src/__tests__/watchTestNamePatternMode.test.js index 9c7987b0bd56..804ea50ea03d 100644 --- a/packages/jest-core/src/__tests__/watchTestNamePatternMode.test.js +++ b/packages/jest-core/src/__tests__/watchTestNamePatternMode.test.js @@ -125,7 +125,7 @@ describe('Watch mode flows', () => { // Runs Jest again runJestMock.mockReset(); stdin.emit(KEYS.ENTER); - expect(runJestMock).toBeCalled(); + expect(runJestMock).toHaveBeenCalled(); // globalConfig is updated with the current pattern expect(runJestMock.mock.calls[0][0].globalConfig).toMatchObject({ diff --git a/packages/jest-fake-timers/src/__tests__/legacyFakeTimers.test.ts b/packages/jest-fake-timers/src/__tests__/legacyFakeTimers.test.ts index 11267959751e..267b5300af5f 100644 --- a/packages/jest-fake-timers/src/__tests__/legacyFakeTimers.test.ts +++ b/packages/jest-fake-timers/src/__tests__/legacyFakeTimers.test.ts @@ -1119,7 +1119,7 @@ describe('FakeTimers', () => { }, 0); timers.runOnlyPendingTimers(); - expect(fn).not.toBeCalled(); + expect(fn).not.toHaveBeenCalled(); }); }); diff --git a/packages/jest-fake-timers/src/__tests__/modernFakeTimers.test.ts b/packages/jest-fake-timers/src/__tests__/modernFakeTimers.test.ts index fd3c7f37a3a1..e7ccb4be52db 100644 --- a/packages/jest-fake-timers/src/__tests__/modernFakeTimers.test.ts +++ b/packages/jest-fake-timers/src/__tests__/modernFakeTimers.test.ts @@ -735,7 +735,7 @@ describe('FakeTimers', () => { }, 0); timers.runOnlyPendingTimers(); - expect(fn).not.toBeCalled(); + expect(fn).not.toHaveBeenCalled(); }); }); diff --git a/packages/jest-haste-map/src/__tests__/index.test.js b/packages/jest-haste-map/src/__tests__/index.test.js index a3b2c6efc923..1e79945424ce 100644 --- a/packages/jest-haste-map/src/__tests__/index.test.js +++ b/packages/jest-haste-map/src/__tests__/index.test.js @@ -1336,7 +1336,7 @@ describe('HasteMap', () => { ], ]); - expect(mockEnd).toBeCalled(); + expect(mockEnd).toHaveBeenCalled(); }); it('tries to crawl using node as a fallback', async () => { @@ -1360,8 +1360,8 @@ describe('HasteMap', () => { const {__hasteMapForTest: data} = await ( await HasteMap.create(defaultConfig) ).build(); - expect(watchman).toBeCalled(); - expect(node).toBeCalled(); + expect(watchman).toHaveBeenCalled(); + expect(node).toHaveBeenCalled(); expect(data.files).toEqual( createMap({ @@ -1401,8 +1401,8 @@ describe('HasteMap', () => { await HasteMap.create(defaultConfig) ).build(); - expect(watchman).toBeCalled(); - expect(node).toBeCalled(); + expect(watchman).toHaveBeenCalled(); + expect(node).toHaveBeenCalled(); expect(data.files).toEqual( createMap({ diff --git a/packages/jest-haste-map/src/crawlers/__tests__/watchman.test.js b/packages/jest-haste-map/src/crawlers/__tests__/watchman.test.js index d9675deabf73..c5ac6436bf4d 100644 --- a/packages/jest-haste-map/src/crawlers/__tests__/watchman.test.js +++ b/packages/jest-haste-map/src/crawlers/__tests__/watchman.test.js @@ -139,7 +139,7 @@ describe('watchman watch', () => { const client = watchman.Client.mock.instances[0]; const calls = client.command.mock.calls; - expect(client.on).toBeCalled(); + expect(client.on).toHaveBeenCalled(); expect(client.on).toBeCalledWith('error', expect.any(Function)); // Call 0 and 1 are for ['watch-project'] @@ -178,7 +178,7 @@ describe('watchman watch', () => { expect(removedFiles).toEqual(new Map()); - expect(client.end).toBeCalled(); + expect(client.end).toHaveBeenCalled(); }); test('updates file map and removedFiles when the clock is given', async () => { @@ -481,7 +481,7 @@ describe('watchman watch', () => { const client = watchman.Client.mock.instances[0]; const calls = client.command.mock.calls; - expect(client.on).toBeCalled(); + expect(client.on).toHaveBeenCalled(); expect(client.on).toBeCalledWith('error', expect.any(Function)); // First 3 calls are for ['watch-project'] @@ -515,7 +515,7 @@ describe('watchman watch', () => { expect(removedFiles).toEqual(new Map()); - expect(client.end).toBeCalled(); + expect(client.end).toHaveBeenCalled(); }); test('SHA-1 requested and available', async () => { diff --git a/packages/jest-runtime/src/__tests__/runtime_jest_fn.js b/packages/jest-runtime/src/__tests__/runtime_jest_fn.js index 2cc2552ec529..07976d788284 100644 --- a/packages/jest-runtime/src/__tests__/runtime_jest_fn.js +++ b/packages/jest-runtime/src/__tests__/runtime_jest_fn.js @@ -22,7 +22,7 @@ describe('Runtime', () => { const mock = root.jest.fn(); expect(mock._isMockFunction).toBe(true); mock(); - expect(mock).toBeCalled(); + expect(mock).toHaveBeenCalled(); }); it('creates mock functions with mock implementations', async () => { @@ -32,7 +32,7 @@ describe('Runtime', () => { expect(mock._isMockFunction).toBe(true); const value = mock('mock'); expect(value).toEqual('mock implementation'); - expect(mock).toBeCalled(); + expect(mock).toHaveBeenCalled(); }); }); @@ -57,13 +57,13 @@ describe('Runtime', () => { const mock2 = root.jest.fn(); mock2(); - expect(mock1).toBeCalled(); - expect(mock2).toBeCalled(); + expect(mock1).toHaveBeenCalled(); + expect(mock2).toHaveBeenCalled(); runtime.clearAllMocks(); - expect(mock1).not.toBeCalled(); - expect(mock2).not.toBeCalled(); + expect(mock1).not.toHaveBeenCalled(); + expect(mock2).not.toHaveBeenCalled(); }); }); }); diff --git a/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts b/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts index 5785e98c05a4..a3dd4802c297 100644 --- a/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts +++ b/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts @@ -561,7 +561,7 @@ describe('ScriptTransformer', () => { getCoverageOptions(), ); - expect(require('test_preprocessor').getCacheKey).toBeCalled(); + expect(require('test_preprocessor').getCacheKey).toHaveBeenCalled(); expect(res1.code).toMatchSnapshot(); @@ -581,7 +581,7 @@ describe('ScriptTransformer', () => { getCoverageOptions(), ); - expect(require('test_preprocessor').getCacheKey).toBeCalled(); + expect(require('test_preprocessor').getCacheKey).toHaveBeenCalled(); expect(res1.code).toMatchSnapshot(); @@ -604,7 +604,9 @@ describe('ScriptTransformer', () => { getCoverageOptions(), ); - expect(require('test_async_preprocessor').getCacheKeyAsync).toBeCalled(); + expect( + require('test_async_preprocessor').getCacheKeyAsync, + ).toHaveBeenCalled(); expect(res1.code).toMatchSnapshot(); @@ -635,8 +637,8 @@ describe('ScriptTransformer', () => { getCoverageOptions(), ); - expect(require('test_preprocessor').getCacheKey).toBeCalled(); - expect(require('css-preprocessor').getCacheKey).toBeCalled(); + expect(require('test_preprocessor').getCacheKey).toHaveBeenCalled(); + expect(require('css-preprocessor').getCacheKey).toHaveBeenCalled(); expect(res1.code).toMatchSnapshot(); expect(res2.code).toMatchSnapshot(); @@ -667,8 +669,10 @@ describe('ScriptTransformer', () => { getCoverageOptions(), ); - expect(require('test_async_preprocessor').getCacheKeyAsync).toBeCalled(); - expect(require('css-preprocessor').getCacheKey).toBeCalled(); + expect( + require('test_async_preprocessor').getCacheKeyAsync, + ).toHaveBeenCalled(); + expect(require('css-preprocessor').getCacheKey).toHaveBeenCalled(); expect(res1.code).toMatchSnapshot(); expect(res2.code).toMatchSnapshot(); @@ -1412,7 +1416,7 @@ describe('ScriptTransformer', () => { scriptTransformer.transform('/fruits/banana.js', getCoverageOptions()); const cachePath = getCachePath(mockFs, config); - expect(writeFileAtomic.sync).toBeCalled(); + expect(writeFileAtomic.sync).toHaveBeenCalled(); expect(writeFileAtomic.sync.mock.calls[0][0]).toBe(cachePath); // Cache the state in `mockFsCopy` @@ -1428,7 +1432,7 @@ describe('ScriptTransformer', () => { expect(fs.readFileSync).toHaveBeenCalledTimes(2); expect(fs.readFileSync).toBeCalledWith('/fruits/banana.js', 'utf8'); expect(fs.readFileSync).toBeCalledWith(cachePath, 'utf8'); - expect(writeFileAtomic.sync).not.toBeCalled(); + expect(writeFileAtomic.sync).not.toHaveBeenCalled(); // Don't read from the cache when `config.cache` is false. jest.resetModules(); @@ -1441,7 +1445,7 @@ describe('ScriptTransformer', () => { expect(fs.readFileSync).toHaveBeenCalledTimes(1); expect(fs.readFileSync).toBeCalledWith('/fruits/banana.js', 'utf8'); expect(fs.readFileSync).not.toBeCalledWith(cachePath, 'utf8'); - expect(writeFileAtomic.sync).toBeCalled(); + expect(writeFileAtomic.sync).toHaveBeenCalled(); }); it('in async mode, reads values from the cache', async () => { @@ -1456,7 +1460,7 @@ describe('ScriptTransformer', () => { ); const cachePath = getCachePath(mockFs, config); - expect(writeFileAtomic.sync).toBeCalled(); + expect(writeFileAtomic.sync).toHaveBeenCalled(); expect(writeFileAtomic.sync.mock.calls[0][0]).toBe(cachePath); // Cache the state in `mockFsCopy` @@ -1475,7 +1479,7 @@ describe('ScriptTransformer', () => { expect(fs.readFileSync).toHaveBeenCalledTimes(2); expect(fs.readFileSync).toBeCalledWith('/fruits/banana.js', 'utf8'); expect(fs.readFileSync).toBeCalledWith(cachePath, 'utf8'); - expect(writeFileAtomic.sync).not.toBeCalled(); + expect(writeFileAtomic.sync).not.toHaveBeenCalled(); // Don't read from the cache when `config.cache` is false. jest.resetModules(); @@ -1491,7 +1495,7 @@ describe('ScriptTransformer', () => { expect(fs.readFileSync).toHaveBeenCalledTimes(1); expect(fs.readFileSync).toBeCalledWith('/fruits/banana.js', 'utf8'); expect(fs.readFileSync).not.toBeCalledWith(cachePath, 'utf8'); - expect(writeFileAtomic.sync).toBeCalled(); + expect(writeFileAtomic.sync).toHaveBeenCalled(); }); it('reads values from the cache when using async preprocessor', async () => { @@ -1506,7 +1510,7 @@ describe('ScriptTransformer', () => { ); const cachePath = getCachePath(mockFs, config); - expect(writeFileAtomic.sync).toBeCalled(); + expect(writeFileAtomic.sync).toHaveBeenCalled(); expect(writeFileAtomic.sync.mock.calls[0][0]).toBe(cachePath); // Cache the state in `mockFsCopy` @@ -1525,7 +1529,7 @@ describe('ScriptTransformer', () => { expect(fs.readFileSync).toHaveBeenCalledTimes(2); expect(fs.readFileSync).toBeCalledWith('/fruits/banana.js', 'utf8'); expect(fs.readFileSync).toBeCalledWith(cachePath, 'utf8'); - expect(writeFileAtomic.sync).not.toBeCalled(); + expect(writeFileAtomic.sync).not.toHaveBeenCalled(); // Don't read from the cache when `config.cache` is false. jest.resetModules(); @@ -1541,7 +1545,7 @@ describe('ScriptTransformer', () => { expect(fs.readFileSync).toHaveBeenCalledTimes(1); expect(fs.readFileSync).toBeCalledWith('/fruits/banana.js', 'utf8'); expect(fs.readFileSync).not.toBeCalledWith(cachePath, 'utf8'); - expect(writeFileAtomic.sync).toBeCalled(); + expect(writeFileAtomic.sync).toHaveBeenCalled(); }); it('reads values from the cache when the file contains colons', async () => { @@ -1556,7 +1560,7 @@ describe('ScriptTransformer', () => { ); const cachePath = getCachePath(mockFs, config); - expect(writeFileAtomic.sync).toBeCalled(); + expect(writeFileAtomic.sync).toHaveBeenCalled(); expect(writeFileAtomic.sync.mock.calls[0][0]).toBe(cachePath); // Cache the state in `mockFsCopy` @@ -1572,7 +1576,7 @@ describe('ScriptTransformer', () => { expect(fs.readFileSync).toHaveBeenCalledTimes(2); expect(fs.readFileSync).toBeCalledWith('/fruits/banana:colon.js', 'utf8'); expect(fs.readFileSync).toBeCalledWith(cachePath, 'utf8'); - expect(writeFileAtomic.sync).not.toBeCalled(); + expect(writeFileAtomic.sync).not.toHaveBeenCalled(); }); it('in async mode, reads values from the cache when the file contains colons', async () => { @@ -1587,7 +1591,7 @@ describe('ScriptTransformer', () => { ); const cachePath = getCachePath(mockFs, config); - expect(writeFileAtomic.sync).toBeCalled(); + expect(writeFileAtomic.sync).toHaveBeenCalled(); expect(writeFileAtomic.sync.mock.calls[0][0]).toBe(cachePath); // Cache the state in `mockFsCopy` @@ -1603,7 +1607,7 @@ describe('ScriptTransformer', () => { expect(fs.readFileSync).toHaveBeenCalledTimes(2); expect(fs.readFileSync).toBeCalledWith('/fruits/banana:colon.js', 'utf8'); expect(fs.readFileSync).toBeCalledWith(cachePath, 'utf8'); - expect(writeFileAtomic.sync).not.toBeCalled(); + expect(writeFileAtomic.sync).not.toHaveBeenCalled(); }); it('with async preprocessor, reads values from the cache when the file contains colons', async () => { @@ -1618,7 +1622,7 @@ describe('ScriptTransformer', () => { ); const cachePath = getCachePath(mockFs, config); - expect(writeFileAtomic.sync).toBeCalled(); + expect(writeFileAtomic.sync).toHaveBeenCalled(); expect(writeFileAtomic.sync.mock.calls[0][0]).toBe(cachePath); // Cache the state in `mockFsCopy` @@ -1634,7 +1638,7 @@ describe('ScriptTransformer', () => { expect(fs.readFileSync).toHaveBeenCalledTimes(2); expect(fs.readFileSync).toBeCalledWith('/fruits/banana:colon.js', 'utf8'); expect(fs.readFileSync).toBeCalledWith(cachePath, 'utf8'); - expect(writeFileAtomic.sync).not.toBeCalled(); + expect(writeFileAtomic.sync).not.toHaveBeenCalled(); }); it('should reuse the value from in-memory cache which is set by custom transformer', async () => { diff --git a/packages/jest-types/__typetests__/expect.test.ts b/packages/jest-types/__typetests__/expect.test.ts index 4fe753a83372..b5b98e58cd14 100644 --- a/packages/jest-types/__typetests__/expect.test.ts +++ b/packages/jest-types/__typetests__/expect.test.ts @@ -193,8 +193,8 @@ expectType(expect(() => {}).toThrow(new Error('error'))); // mock matchers -expectType(expect(jest.fn()).toBeCalled()); -expectError(expect(jest.fn()).toBeCalled('value')); +expectType(expect(jest.fn()).toHaveBeenCalled()); +expectError(expect(jest.fn()).toHaveBeenCalled('value')); expectType(expect(jest.fn()).toHaveBeenCalled()); expectError(expect(jest.fn()).toHaveBeenCalled(false)); diff --git a/packages/jest-util/src/__tests__/deepCyclicCopy.test.ts b/packages/jest-util/src/__tests__/deepCyclicCopy.test.ts index 71ac408dec55..9663338368f7 100644 --- a/packages/jest-util/src/__tests__/deepCyclicCopy.test.ts +++ b/packages/jest-util/src/__tests__/deepCyclicCopy.test.ts @@ -31,7 +31,7 @@ it('does not execute getters/setters, but copies them', () => { const copy = deepCyclicCopy(obj); expect(Object.getOwnPropertyDescriptor(copy, 'foo')).toBeDefined(); - expect(fn).not.toBeCalled(); + expect(fn).not.toHaveBeenCalled(); }); it('copies symbols', () => { diff --git a/packages/jest-validate/src/__tests__/validate.test.ts b/packages/jest-validate/src/__tests__/validate.test.ts index ff0e8572ba13..72daeea9f53d 100644 --- a/packages/jest-validate/src/__tests__/validate.test.ts +++ b/packages/jest-validate/src/__tests__/validate.test.ts @@ -121,7 +121,7 @@ test('respects recursiveDenylist', () => { validate(config, {exampleConfig}); - expect(console.warn).toBeCalled(); + expect(console.warn).toHaveBeenCalled(); console.warn.mockReset(); @@ -130,7 +130,7 @@ test('respects recursiveDenylist', () => { recursiveDenylist: ['something.nested'], }); - expect(console.warn).not.toBeCalled(); + expect(console.warn).not.toHaveBeenCalled(); console.warn = warn; }); @@ -285,7 +285,7 @@ test('Comments in config JSON using "//" key are not warned', () => { validate(config, { exampleConfig: validConfig, }); - expect(console.warn).not.toBeCalled(); + expect(console.warn).not.toHaveBeenCalled(); console.warn.mockReset(); @@ -293,7 +293,7 @@ test('Comments in config JSON using "//" key are not warned', () => { exampleConfig: validConfig, recursiveDenylist: ['myCustomKey' as "don't validate this"], }); - expect(console.warn).not.toBeCalled(); + expect(console.warn).not.toHaveBeenCalled(); console.warn.mockRestore(); }); diff --git a/packages/jest-worker/src/__tests__/WorkerPool.test.js b/packages/jest-worker/src/__tests__/WorkerPool.test.js index 91283ef514b8..8945c5d9d4ce 100644 --- a/packages/jest-worker/src/__tests__/WorkerPool.test.js +++ b/packages/jest-worker/src/__tests__/WorkerPool.test.js @@ -63,7 +63,7 @@ describe('WorkerPool', () => { workerId: 0, workerPath: '/path', }); - expect(NodeThreadWorker).not.toBeCalled(); + expect(NodeThreadWorker).not.toHaveBeenCalled(); expect(workerPool._workers[0].send).toBeCalledWith( {foo: 'bar'}, onStart, @@ -93,7 +93,7 @@ describe('WorkerPool', () => { workerId: 0, workerPath: '/path', }); - expect(ChildProcessWorker).not.toBeCalled(); + expect(ChildProcessWorker).not.toHaveBeenCalled(); expect(workerPool._workers[0].send).toBeCalledWith( {foo: 'bar'}, onStart, @@ -122,7 +122,7 @@ describe('WorkerPool', () => { workerId: 0, workerPath: '/path', }); - expect(NodeThreadWorker).not.toBeCalled(); + expect(NodeThreadWorker).not.toHaveBeenCalled(); expect(workerPool._workers[0].send).toBeCalledWith( {foo: 'bar'}, onStart, diff --git a/packages/pretty-format/src/__tests__/prettyFormat.test.ts b/packages/pretty-format/src/__tests__/prettyFormat.test.ts index 0d2662ef93ba..43931346334b 100644 --- a/packages/pretty-format/src/__tests__/prettyFormat.test.ts +++ b/packages/pretty-format/src/__tests__/prettyFormat.test.ts @@ -894,8 +894,8 @@ describe('prettyFormat()', () => { ).toEqual( `Set {\n Object {\n "apple": "banana",\n "toJSON": [Function ${name}],\n },\n}`, ); - expect((set as any).toJSON).not.toBeCalled(); - expect(value.toJSON).not.toBeCalled(); + expect((set as any).toJSON).not.toHaveBeenCalled(); + expect(value.toJSON).not.toHaveBeenCalled(); }); describe('min', () => { From 6de9ca284c40a6595088f0fa67b0d71c2aed2abb Mon Sep 17 00:00:00 2001 From: EduardoSCosta Date: Mon, 29 Aug 2022 17:01:38 -0300 Subject: [PATCH 03/13] chore: remove .toBeCalledTimes() matcher --- e2e/__tests__/isolateModules.test.ts | 2 +- .../__tests__/infinite_timer_game.test.js | 4 +- examples/timer/__tests__/timer_game.test.js | 6 +- examples/typescript/__tests__/calc.test.ts | 2 +- .../__snapshots__/spyMatchers.test.ts.snap | 144 ------------------ .../expect/src/__tests__/spyMatchers.test.ts | 136 ++++++++--------- packages/expect/src/spyMatchers.ts | 1 - packages/expect/src/types.ts | 4 - .../src/__tests__/TestScheduler.test.js | 110 ++++++------- .../__tests__/GitHubActionsReporter.test.ts | 8 +- .../src/__tests__/testRunner.test.ts | 2 +- .../src/__tests__/ScriptTransformer.test.ts | 32 ++-- .../jest-types/__typetests__/expect.test.ts | 6 +- .../jest-worker/src/__tests__/Farm.test.js | 4 +- 14 files changed, 155 insertions(+), 306 deletions(-) diff --git a/e2e/__tests__/isolateModules.test.ts b/e2e/__tests__/isolateModules.test.ts index 25ecd76fac0f..3d4aac63d78c 100644 --- a/e2e/__tests__/isolateModules.test.ts +++ b/e2e/__tests__/isolateModules.test.ts @@ -45,7 +45,7 @@ test('works with mocks', () => { require("./read"); }); - expect(configGetMock).toBeCalledTimes(1); + expect(configGetMock).toHaveBeenCalledTimes(1); }) `, }); diff --git a/examples/timer/__tests__/infinite_timer_game.test.js b/examples/timer/__tests__/infinite_timer_game.test.js index c2f8e8e98041..e1c87f03d3b8 100644 --- a/examples/timer/__tests__/infinite_timer_game.test.js +++ b/examples/timer/__tests__/infinite_timer_game.test.js @@ -13,7 +13,7 @@ it('schedules a 10-second timer after 1 second', () => { // At this point in time, there should have been a single call to // setTimeout to schedule the end of the game in 1 second. - expect(setTimeout).toBeCalledTimes(1); + expect(setTimeout).toHaveBeenCalledTimes(1); expect(setTimeout).toHaveBeenNthCalledWith(1, expect.any(Function), 1000); // Fast forward and exhaust only currently pending timers @@ -25,6 +25,6 @@ it('schedules a 10-second timer after 1 second', () => { // And it should have created a new timer to start the game over in // 10 seconds - expect(setTimeout).toBeCalledTimes(2); + expect(setTimeout).toHaveBeenCalledTimes(2); expect(setTimeout).toHaveBeenNthCalledWith(2, expect.any(Function), 10000); }); diff --git a/examples/timer/__tests__/timer_game.test.js b/examples/timer/__tests__/timer_game.test.js index 70df7fb37d3e..c00ccc5b89ee 100644 --- a/examples/timer/__tests__/timer_game.test.js +++ b/examples/timer/__tests__/timer_game.test.js @@ -12,7 +12,7 @@ describe('timerGame', () => { const timerGame = require('../timerGame'); timerGame(); - expect(setTimeout).toBeCalledTimes(1); + expect(setTimeout).toHaveBeenCalledTimes(1); expect(setTimeout).toBeCalledWith(expect.any(Function), 1000); }); @@ -30,7 +30,7 @@ describe('timerGame', () => { // Now our callback should have been called! expect(callback).toHaveBeenCalled(); - expect(callback).toBeCalledTimes(1); + expect(callback).toHaveBeenCalledTimes(1); }); it('calls the callback after 1 second via advanceTimersByTime', () => { @@ -47,6 +47,6 @@ describe('timerGame', () => { // Now our callback should have been called! expect(callback).toHaveBeenCalled(); - expect(callback).toBeCalledTimes(1); + expect(callback).toHaveBeenCalledTimes(1); }); }); diff --git a/examples/typescript/__tests__/calc.test.ts b/examples/typescript/__tests__/calc.test.ts index 817bbb86f9fe..af6c36391ba0 100644 --- a/examples/typescript/__tests__/calc.test.ts +++ b/examples/typescript/__tests__/calc.test.ts @@ -78,7 +78,7 @@ describe('calc - mocks', () => { expect(memoryResult).toEqual(2); expect(sumResult2).toEqual(4); expect(clearResult).toEqual(4); - expect(MockMemory.prototype.reset).toBeCalledTimes(1); + expect(MockMemory.prototype.reset).toHaveBeenCalledTimes(1); }); it('throws an error when invalid Op is passed', () => { diff --git a/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap b/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap index ac363e888745..fe698dc4b1a0 100644 --- a/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap +++ b/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap @@ -819,150 +819,6 @@ Expected: not undefined Number of returns: 1 `; -exports[`toBeCalledTimes .not only accepts a number argument 1`] = ` -expect(received).not.toBeCalledTimes(expected) - -Matcher error: expected value must be a non-negative integer - -Expected has type: object -Expected has value: {} -`; - -exports[`toBeCalledTimes .not only accepts a number argument 2`] = ` -expect(received).not.toBeCalledTimes(expected) - -Matcher error: expected value must be a non-negative integer - -Expected has type: array -Expected has value: [] -`; - -exports[`toBeCalledTimes .not only accepts a number argument 3`] = ` -expect(received).not.toBeCalledTimes(expected) - -Matcher error: expected value must be a non-negative integer - -Expected has type: boolean -Expected has value: true -`; - -exports[`toBeCalledTimes .not only accepts a number argument 4`] = ` -expect(received).not.toBeCalledTimes(expected) - -Matcher error: expected value must be a non-negative integer - -Expected has type: string -Expected has value: "a" -`; - -exports[`toBeCalledTimes .not only accepts a number argument 5`] = ` -expect(received).not.toBeCalledTimes(expected) - -Matcher error: expected value must be a non-negative integer - -Expected has type: map -Expected has value: Map {} -`; - -exports[`toBeCalledTimes .not only accepts a number argument 6`] = ` -expect(received).not.toBeCalledTimes(expected) - -Matcher error: expected value must be a non-negative integer - -Expected has type: function -Expected has value: [Function anonymous] -`; - -exports[`toBeCalledTimes .not passes if function called less than expected times 1`] = ` -expect(jest.fn()).toBeCalledTimes(expected) - -Expected number of calls: 2 -Received number of calls: 1 -`; - -exports[`toBeCalledTimes .not passes if function called more than expected times 1`] = ` -expect(jest.fn()).toBeCalledTimes(expected) - -Expected number of calls: 2 -Received number of calls: 3 -`; - -exports[`toBeCalledTimes .not works only on spies or jest.fn 1`] = ` -expect(received).not.toBeCalledTimes(expected) - -Matcher error: received value must be a mock or spy function - -Received has type: function -Received has value: [Function fn] -`; - -exports[`toBeCalledTimes includes the custom mock name in the error message 1`] = ` -expect(named-mock).toBeCalledTimes(expected) - -Expected number of calls: 2 -Received number of calls: 1 -`; - -exports[`toBeCalledTimes only accepts a number argument 1`] = ` -expect(received).toBeCalledTimes(expected) - -Matcher error: expected value must be a non-negative integer - -Expected has type: object -Expected has value: {} -`; - -exports[`toBeCalledTimes only accepts a number argument 2`] = ` -expect(received).toBeCalledTimes(expected) - -Matcher error: expected value must be a non-negative integer - -Expected has type: array -Expected has value: [] -`; - -exports[`toBeCalledTimes only accepts a number argument 3`] = ` -expect(received).toBeCalledTimes(expected) - -Matcher error: expected value must be a non-negative integer - -Expected has type: boolean -Expected has value: true -`; - -exports[`toBeCalledTimes only accepts a number argument 4`] = ` -expect(received).toBeCalledTimes(expected) - -Matcher error: expected value must be a non-negative integer - -Expected has type: string -Expected has value: "a" -`; - -exports[`toBeCalledTimes only accepts a number argument 5`] = ` -expect(received).toBeCalledTimes(expected) - -Matcher error: expected value must be a non-negative integer - -Expected has type: map -Expected has value: Map {} -`; - -exports[`toBeCalledTimes only accepts a number argument 6`] = ` -expect(received).toBeCalledTimes(expected) - -Matcher error: expected value must be a non-negative integer - -Expected has type: function -Expected has value: [Function anonymous] -`; - -exports[`toBeCalledTimes passes if function called equal to expected times 1`] = ` -expect(spy).not.toBeCalledTimes(expected) - -Expected number of calls: not 2 -`; - exports[`toBeCalledWith includes the custom mock name in the error message 1`] = ` expect(named-mock).not.toBeCalledWith(...expected) diff --git a/packages/expect/src/__tests__/spyMatchers.test.ts b/packages/expect/src/__tests__/spyMatchers.test.ts index 93b8b6fd0757..ccf29923a315 100644 --- a/packages/expect/src/__tests__/spyMatchers.test.ts +++ b/packages/expect/src/__tests__/spyMatchers.test.ts @@ -92,95 +92,93 @@ describe('toHaveBeenCalled', () => { }); }); -['toBeCalledTimes', 'toHaveBeenCalledTimes'].forEach(calledTimes => { - describe(`${calledTimes}`, () => { - test('.not works only on spies or jest.fn', () => { - const fn = function fn() {}; +describe('toHaveBeenCalledTimes', () => { + test('.not works only on spies or jest.fn', () => { + const fn = function fn() {}; - expect(() => - jestExpect(fn).not[calledTimes](2), - ).toThrowErrorMatchingSnapshot(); - }); + expect(() => + jestExpect(fn).not.toHaveBeenCalledTimes(2), + ).toThrowErrorMatchingSnapshot(); + }); - test('only accepts a number argument', () => { - const fn = jest.fn(); - fn(); - jestExpect(fn)[calledTimes](1); + test('only accepts a number argument', () => { + const fn = jest.fn(); + fn(); + jestExpect(fn).toHaveBeenCalledTimes(1); - [{}, [], true, 'a', new Map(), () => {}].forEach(value => { - expect(() => - jestExpect(fn)[calledTimes](value), - ).toThrowErrorMatchingSnapshot(); - }); + [{}, [], true, 'a', new Map(), () => {}].forEach(value => { + expect(() => + jestExpect(fn).toHaveBeenCalledTimes(value), + ).toThrowErrorMatchingSnapshot(); }); + }); - test('.not only accepts a number argument', () => { - const fn = jest.fn(); - jestExpect(fn).not[calledTimes](1); + test('.not only accepts a number argument', () => { + const fn = jest.fn(); + jestExpect(fn).not.toHaveBeenCalledTimes(1); - [{}, [], true, 'a', new Map(), () => {}].forEach(value => { - expect(() => - jestExpect(fn).not[calledTimes](value), - ).toThrowErrorMatchingSnapshot(); - }); + [{}, [], true, 'a', new Map(), () => {}].forEach(value => { + expect(() => + jestExpect(fn).not.toHaveBeenCalledTimes(value), + ).toThrowErrorMatchingSnapshot(); }); + }); - test('passes if function called equal to expected times', () => { - const fn = jest.fn(); - fn(); - fn(); + test('passes if function called equal to expected times', () => { + const fn = jest.fn(); + fn(); + fn(); - const spy = createSpy(fn); - jestExpect(spy)[calledTimes](2); - jestExpect(fn)[calledTimes](2); + const spy = createSpy(fn); + jestExpect(spy).toHaveBeenCalledTimes(2); + jestExpect(fn).toHaveBeenCalledTimes(2); - expect(() => - jestExpect(spy).not[calledTimes](2), - ).toThrowErrorMatchingSnapshot(); - }); + expect(() => + jestExpect(spy).not.toHaveBeenCalledTimes(2), + ).toThrowErrorMatchingSnapshot(); + }); - test('.not passes if function called more than expected times', () => { - const fn = jest.fn(); - fn(); - fn(); - fn(); + test('.not passes if function called more than expected times', () => { + const fn = jest.fn(); + fn(); + fn(); + fn(); - const spy = createSpy(fn); - jestExpect(spy)[calledTimes](3); - jestExpect(spy).not[calledTimes](2); + const spy = createSpy(fn); + jestExpect(spy).toHaveBeenCalledTimes(3); + jestExpect(spy).not.toHaveBeenCalledTimes(2); - jestExpect(fn)[calledTimes](3); - jestExpect(fn).not[calledTimes](2); + jestExpect(fn).toHaveBeenCalledTimes(3); + jestExpect(fn).not.toHaveBeenCalledTimes(2); - expect(() => - jestExpect(fn)[calledTimes](2), - ).toThrowErrorMatchingSnapshot(); - }); + expect(() => + jestExpect(fn).toHaveBeenCalledTimes(2), + ).toThrowErrorMatchingSnapshot(); + }); - test('.not passes if function called less than expected times', () => { - const fn = jest.fn(); - fn(); + test('.not passes if function called less than expected times', () => { + const fn = jest.fn(); + fn(); - const spy = createSpy(fn); - jestExpect(spy)[calledTimes](1); - jestExpect(spy).not[calledTimes](2); + const spy = createSpy(fn); + jestExpect(spy).toHaveBeenCalledTimes(1); + jestExpect(spy).not.toHaveBeenCalledTimes(2); - jestExpect(fn)[calledTimes](1); - jestExpect(fn).not[calledTimes](2); + jestExpect(fn).toHaveBeenCalledTimes(1); + jestExpect(fn).not.toHaveBeenCalledTimes(2); - expect(() => - jestExpect(fn)[calledTimes](2), - ).toThrowErrorMatchingSnapshot(); - }); + expect(() => + jestExpect(fn).toHaveBeenCalledTimes(2), + ).toThrowErrorMatchingSnapshot(); + }); - test('includes the custom mock name in the error message', () => { - const fn = jest.fn().mockName('named-mock'); - fn(); + test('includes the custom mock name in the error message', () => { + const fn = jest.fn().mockName('named-mock'); + fn(); - expect(() => - jestExpect(fn)[calledTimes](2), - ).toThrowErrorMatchingSnapshot(); - }); + expect(() => + jestExpect(fn).toHaveBeenCalledTimes(2), + ).toThrowErrorMatchingSnapshot(); }); }); diff --git a/packages/expect/src/spyMatchers.ts b/packages/expect/src/spyMatchers.ts index c8ea6bf188a4..126ebd98afb6 100644 --- a/packages/expect/src/spyMatchers.ts +++ b/packages/expect/src/spyMatchers.ts @@ -1140,7 +1140,6 @@ const spyMatchers: MatchersObject = { lastReturnedWith: createLastReturnedMatcher('lastReturnedWith'), nthCalledWith: createNthCalledWithMatcher('nthCalledWith'), nthReturnedWith: createNthReturnedWithMatcher('nthReturnedWith'), - toBeCalledTimes: createToBeCalledTimesMatcher('toBeCalledTimes'), toBeCalledWith: createToBeCalledWithMatcher('toBeCalledWith'), toHaveBeenCalled: createToBeCalledMatcher('toHaveBeenCalled'), toHaveBeenCalledTimes: createToBeCalledTimesMatcher('toHaveBeenCalledTimes'), diff --git a/packages/expect/src/types.ts b/packages/expect/src/types.ts index d8d902e8db64..f1679103d4ea 100644 --- a/packages/expect/src/types.ts +++ b/packages/expect/src/types.ts @@ -153,10 +153,6 @@ export interface Matchers> { * Don't use `toBe` with floating-point numbers. */ toBe(expected: unknown): R; - /** - * Ensures that a mock function is called an exact number of times. - */ - toBeCalledTimes(expected: number): R; /** * Ensure that a mock function is called with specific arguments. */ diff --git a/packages/jest-core/src/__tests__/TestScheduler.test.js b/packages/jest-core/src/__tests__/TestScheduler.test.js index 69f98cb2c6f0..a8c222bbb486 100644 --- a/packages/jest-core/src/__tests__/TestScheduler.test.js +++ b/packages/jest-core/src/__tests__/TestScheduler.test.js @@ -69,12 +69,12 @@ describe('reporters', () => { {}, ); - expect(DefaultReporter).toBeCalledTimes(1); - expect(VerboseReporter).toBeCalledTimes(0); - expect(GitHubActionsReporter).toBeCalledTimes(0); - expect(NotifyReporter).toBeCalledTimes(0); - expect(CoverageReporter).toBeCalledTimes(0); - expect(SummaryReporter).toBeCalledTimes(1); + expect(DefaultReporter).toHaveBeenCalledTimes(1); + expect(VerboseReporter).toHaveBeenCalledTimes(0); + expect(GitHubActionsReporter).toHaveBeenCalledTimes(0); + expect(NotifyReporter).toHaveBeenCalledTimes(0); + expect(CoverageReporter).toHaveBeenCalledTimes(0); + expect(SummaryReporter).toHaveBeenCalledTimes(1); }); test('does not enable any reporters, if empty list is passed', async () => { @@ -86,12 +86,12 @@ describe('reporters', () => { {}, ); - expect(DefaultReporter).toBeCalledTimes(0); - expect(VerboseReporter).toBeCalledTimes(0); - expect(GitHubActionsReporter).toBeCalledTimes(0); - expect(NotifyReporter).toBeCalledTimes(0); - expect(CoverageReporter).toBeCalledTimes(0); - expect(SummaryReporter).toBeCalledTimes(0); + expect(DefaultReporter).toHaveBeenCalledTimes(0); + expect(VerboseReporter).toHaveBeenCalledTimes(0); + expect(GitHubActionsReporter).toHaveBeenCalledTimes(0); + expect(NotifyReporter).toHaveBeenCalledTimes(0); + expect(CoverageReporter).toHaveBeenCalledTimes(0); + expect(SummaryReporter).toHaveBeenCalledTimes(0); }); test('sets up default reporters', async () => { @@ -103,12 +103,12 @@ describe('reporters', () => { {}, ); - expect(DefaultReporter).toBeCalledTimes(1); - expect(VerboseReporter).toBeCalledTimes(0); - expect(GitHubActionsReporter).toBeCalledTimes(0); - expect(NotifyReporter).toBeCalledTimes(0); - expect(CoverageReporter).toBeCalledTimes(0); - expect(SummaryReporter).toBeCalledTimes(1); + expect(DefaultReporter).toHaveBeenCalledTimes(1); + expect(VerboseReporter).toHaveBeenCalledTimes(0); + expect(GitHubActionsReporter).toHaveBeenCalledTimes(0); + expect(NotifyReporter).toHaveBeenCalledTimes(0); + expect(CoverageReporter).toHaveBeenCalledTimes(0); + expect(SummaryReporter).toHaveBeenCalledTimes(1); }); test('sets up verbose reporter', async () => { @@ -121,12 +121,12 @@ describe('reporters', () => { {}, ); - expect(DefaultReporter).toBeCalledTimes(0); - expect(VerboseReporter).toBeCalledTimes(1); - expect(GitHubActionsReporter).toBeCalledTimes(0); - expect(NotifyReporter).toBeCalledTimes(0); - expect(CoverageReporter).toBeCalledTimes(0); - expect(SummaryReporter).toBeCalledTimes(1); + expect(DefaultReporter).toHaveBeenCalledTimes(0); + expect(VerboseReporter).toHaveBeenCalledTimes(1); + expect(GitHubActionsReporter).toHaveBeenCalledTimes(0); + expect(NotifyReporter).toHaveBeenCalledTimes(0); + expect(CoverageReporter).toHaveBeenCalledTimes(0); + expect(SummaryReporter).toHaveBeenCalledTimes(1); }); test('sets up github actions reporter', async () => { @@ -141,12 +141,12 @@ describe('reporters', () => { {}, ); - expect(DefaultReporter).toBeCalledTimes(1); - expect(VerboseReporter).toBeCalledTimes(0); - expect(GitHubActionsReporter).toBeCalledTimes(1); - expect(NotifyReporter).toBeCalledTimes(0); - expect(CoverageReporter).toBeCalledTimes(0); - expect(SummaryReporter).toBeCalledTimes(1); + expect(DefaultReporter).toHaveBeenCalledTimes(1); + expect(VerboseReporter).toHaveBeenCalledTimes(0); + expect(GitHubActionsReporter).toHaveBeenCalledTimes(1); + expect(NotifyReporter).toHaveBeenCalledTimes(0); + expect(CoverageReporter).toHaveBeenCalledTimes(0); + expect(SummaryReporter).toHaveBeenCalledTimes(1); }); test('sets up notify reporter', async () => { @@ -159,12 +159,12 @@ describe('reporters', () => { {}, ); - expect(DefaultReporter).toBeCalledTimes(1); - expect(VerboseReporter).toBeCalledTimes(0); - expect(GitHubActionsReporter).toBeCalledTimes(0); - expect(NotifyReporter).toBeCalledTimes(1); - expect(CoverageReporter).toBeCalledTimes(0); - expect(SummaryReporter).toBeCalledTimes(1); + expect(DefaultReporter).toHaveBeenCalledTimes(1); + expect(VerboseReporter).toHaveBeenCalledTimes(0); + expect(GitHubActionsReporter).toHaveBeenCalledTimes(0); + expect(NotifyReporter).toHaveBeenCalledTimes(1); + expect(CoverageReporter).toHaveBeenCalledTimes(0); + expect(SummaryReporter).toHaveBeenCalledTimes(1); }); test('sets up coverage reporter', async () => { @@ -177,12 +177,12 @@ describe('reporters', () => { {}, ); - expect(DefaultReporter).toBeCalledTimes(1); - expect(VerboseReporter).toBeCalledTimes(0); - expect(GitHubActionsReporter).toBeCalledTimes(0); - expect(NotifyReporter).toBeCalledTimes(0); - expect(CoverageReporter).toBeCalledTimes(1); - expect(SummaryReporter).toBeCalledTimes(1); + expect(DefaultReporter).toHaveBeenCalledTimes(1); + expect(VerboseReporter).toHaveBeenCalledTimes(0); + expect(GitHubActionsReporter).toHaveBeenCalledTimes(0); + expect(NotifyReporter).toHaveBeenCalledTimes(0); + expect(CoverageReporter).toHaveBeenCalledTimes(1); + expect(SummaryReporter).toHaveBeenCalledTimes(1); }); test('allows enabling summary reporter separately', async () => { @@ -194,12 +194,12 @@ describe('reporters', () => { {}, ); - expect(DefaultReporter).toBeCalledTimes(0); - expect(VerboseReporter).toBeCalledTimes(0); - expect(GitHubActionsReporter).toBeCalledTimes(0); - expect(NotifyReporter).toBeCalledTimes(0); - expect(CoverageReporter).toBeCalledTimes(0); - expect(SummaryReporter).toBeCalledTimes(1); + expect(DefaultReporter).toHaveBeenCalledTimes(0); + expect(VerboseReporter).toHaveBeenCalledTimes(0); + expect(GitHubActionsReporter).toHaveBeenCalledTimes(0); + expect(NotifyReporter).toHaveBeenCalledTimes(0); + expect(CoverageReporter).toHaveBeenCalledTimes(0); + expect(SummaryReporter).toHaveBeenCalledTimes(1); }); test('sets up custom reporter', async () => { @@ -214,13 +214,13 @@ describe('reporters', () => { {}, ); - expect(DefaultReporter).toBeCalledTimes(1); - expect(VerboseReporter).toBeCalledTimes(0); - expect(GitHubActionsReporter).toBeCalledTimes(0); - expect(NotifyReporter).toBeCalledTimes(0); - expect(CoverageReporter).toBeCalledTimes(0); - expect(SummaryReporter).toBeCalledTimes(1); - expect(CustomReporter).toBeCalledTimes(1); + expect(DefaultReporter).toHaveBeenCalledTimes(1); + expect(VerboseReporter).toHaveBeenCalledTimes(0); + expect(GitHubActionsReporter).toHaveBeenCalledTimes(0); + expect(NotifyReporter).toHaveBeenCalledTimes(0); + expect(CoverageReporter).toHaveBeenCalledTimes(0); + expect(SummaryReporter).toHaveBeenCalledTimes(1); + expect(CustomReporter).toHaveBeenCalledTimes(1); }); }); diff --git a/packages/jest-reporters/src/__tests__/GitHubActionsReporter.test.ts b/packages/jest-reporters/src/__tests__/GitHubActionsReporter.test.ts index ddc81279417f..7d1ce8a1e705 100644 --- a/packages/jest-reporters/src/__tests__/GitHubActionsReporter.test.ts +++ b/packages/jest-reporters/src/__tests__/GitHubActionsReporter.test.ts @@ -81,7 +81,7 @@ describe('logs error annotation', () => { ], } as TestResult); - expect(jest.mocked(process.stderr.write)).toBeCalledTimes(1); + expect(jest.mocked(process.stderr.write)).toHaveBeenCalledTimes(1); expect(jest.mocked(process.stderr.write).mock.calls[0]).toMatchSnapshot(); }); @@ -98,7 +98,7 @@ describe('logs error annotation', () => { } as TestResult, ); - expect(jest.mocked(process.stderr.write)).toBeCalledTimes(1); + expect(jest.mocked(process.stderr.write)).toHaveBeenCalledTimes(1); expect(jest.mocked(process.stderr.write).mock.calls[0]).toMatchSnapshot(); }); @@ -112,7 +112,7 @@ describe('logs error annotation', () => { ], } as TestResult); - expect(jest.mocked(process.stderr.write)).toBeCalledTimes(1); + expect(jest.mocked(process.stderr.write)).toHaveBeenCalledTimes(1); expect(jest.mocked(process.stderr.write).mock.calls[0]).toMatchSnapshot(); }); }); @@ -129,7 +129,7 @@ describe('logs warning annotation before logging errors', () => { ], } as TestResult); - expect(jest.mocked(process.stderr.write)).toBeCalledTimes(2); + expect(jest.mocked(process.stderr.write)).toHaveBeenCalledTimes(2); expect(jest.mocked(process.stderr.write).mock.calls).toMatchSnapshot(); }); }); diff --git a/packages/jest-runner/src/__tests__/testRunner.test.ts b/packages/jest-runner/src/__tests__/testRunner.test.ts index 85ee76e0f5d3..fe2a53706b6f 100644 --- a/packages/jest-runner/src/__tests__/testRunner.test.ts +++ b/packages/jest-runner/src/__tests__/testRunner.test.ts @@ -45,7 +45,7 @@ test('injects the serializable module map into each worker in watch mode', async {serial: false}, ); - expect(mockWorkerFarm.worker).toBeCalledTimes(2); + expect(mockWorkerFarm.worker).toHaveBeenCalledTimes(2); expect(mockWorkerFarm.worker).nthCalledWith(1, { config, diff --git a/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts b/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts index a3dd4802c297..cb8a82b9ecb5 100644 --- a/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts +++ b/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts @@ -707,7 +707,7 @@ describe('ScriptTransformer', () => { ); expect(result.sourceMapPath).toEqual(expect.any(String)); const mapStr = JSON.stringify(map); - expect(writeFileAtomic.sync).toBeCalledTimes(2); + expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); expect(writeFileAtomic.sync).toBeCalledWith(result.sourceMapPath, mapStr, { encoding: 'utf8', fsync: false, @@ -737,7 +737,7 @@ describe('ScriptTransformer', () => { ); expect(result.sourceMapPath).toEqual(expect.any(String)); const mapStr = JSON.stringify(map); - expect(writeFileAtomic.sync).toBeCalledTimes(2); + expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); expect(writeFileAtomic.sync).toBeCalledWith(result.sourceMapPath, mapStr, { encoding: 'utf8', fsync: false, @@ -769,7 +769,7 @@ describe('ScriptTransformer', () => { ); expect(result.sourceMapPath).toEqual(expect.any(String)); const mapStr = JSON.stringify(map); - expect(writeFileAtomic.sync).toBeCalledTimes(2); + expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); expect(writeFileAtomic.sync).toBeCalledWith(result.sourceMapPath, mapStr, { encoding: 'utf8', fsync: false, @@ -803,7 +803,7 @@ describe('ScriptTransformer', () => { getCoverageOptions(), ); expect(result.sourceMapPath).toEqual(expect.any(String)); - expect(writeFileAtomic.sync).toBeCalledTimes(2); + expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); expect(writeFileAtomic.sync).toBeCalledWith( result.sourceMapPath, sourceMap, @@ -838,7 +838,7 @@ describe('ScriptTransformer', () => { getCoverageOptions(), ); expect(result.sourceMapPath).toEqual(expect.any(String)); - expect(writeFileAtomic.sync).toBeCalledTimes(2); + expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); expect(writeFileAtomic.sync).toBeCalledWith( result.sourceMapPath, sourceMap, @@ -873,7 +873,7 @@ describe('ScriptTransformer', () => { getCoverageOptions(), ); expect(result.sourceMapPath).toEqual(expect.any(String)); - expect(writeFileAtomic.sync).toBeCalledTimes(2); + expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); expect(writeFileAtomic.sync).toBeCalledWith( result.sourceMapPath, sourceMap, @@ -914,7 +914,7 @@ describe('ScriptTransformer', () => { getCoverageOptions({collectCoverage: true}), ); expect(result.sourceMapPath).toBeNull(); - expect(writeFileAtomic.sync).toBeCalledTimes(1); + expect(writeFileAtomic.sync).toHaveBeenCalledTimes(1); expect(console.warn).toHaveBeenCalledTimes(1); expect(console.warn.mock.calls[0][0]).toMatchSnapshot(); @@ -954,7 +954,7 @@ describe('ScriptTransformer', () => { getCoverageOptions({collectCoverage: true}), ); expect(result.sourceMapPath).toBeNull(); - expect(writeFileAtomic.sync).toBeCalledTimes(1); + expect(writeFileAtomic.sync).toHaveBeenCalledTimes(1); expect(console.warn).toHaveBeenCalledTimes(1); expect(console.warn.mock.calls[0][0]).toMatchSnapshot(); @@ -994,7 +994,7 @@ describe('ScriptTransformer', () => { getCoverageOptions({collectCoverage: true}), ); expect(result.sourceMapPath).toBeNull(); - expect(writeFileAtomic.sync).toBeCalledTimes(1); + expect(writeFileAtomic.sync).toHaveBeenCalledTimes(1); expect(console.warn).toHaveBeenCalledTimes(1); expect(console.warn.mock.calls[0][0]).toMatchSnapshot(); @@ -1024,7 +1024,7 @@ describe('ScriptTransformer', () => { getCoverageOptions(), ); expect(result.sourceMapPath).toEqual(expect.any(String)); - expect(writeFileAtomic.sync).toBeCalledTimes(2); + expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); expect(writeFileAtomic.sync).toBeCalledWith( result.sourceMapPath, JSON.stringify(map), @@ -1131,7 +1131,7 @@ describe('ScriptTransformer', () => { getCoverageOptions({collectCoverage: true}), ); expect(result.sourceMapPath).toEqual(expect.any(String)); - expect(writeFileAtomic.sync).toBeCalledTimes(2); + expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); expect(writeFileAtomic.sync).toBeCalledWith( result.sourceMapPath, JSON.stringify(instrumentedCodeMap), @@ -1176,7 +1176,7 @@ describe('ScriptTransformer', () => { getCoverageOptions({collectCoverage: true}), ); expect(result.sourceMapPath).toEqual(expect.any(String)); - expect(writeFileAtomic.sync).toBeCalledTimes(2); + expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); expect(writeFileAtomic.sync).toBeCalledWith( result.sourceMapPath, JSON.stringify(instrumentedCodeMap), @@ -1223,7 +1223,7 @@ describe('ScriptTransformer', () => { getCoverageOptions({collectCoverage: true}), ); expect(result.sourceMapPath).toEqual(expect.any(String)); - expect(writeFileAtomic.sync).toBeCalledTimes(2); + expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); expect(writeFileAtomic.sync).toBeCalledWith( result.sourceMapPath, JSON.stringify(instrumentedCodeMap), @@ -1259,7 +1259,7 @@ describe('ScriptTransformer', () => { getCoverageOptions({collectCoverage: true}), ); expect(result.sourceMapPath).toEqual(expect.any(String)); - expect(writeFileAtomic.sync).toBeCalledTimes(2); + expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); expect(writeFileAtomic.sync).toBeCalledWith( result.sourceMapPath, JSON.stringify(instrumentedCodeMap), @@ -1295,7 +1295,7 @@ describe('ScriptTransformer', () => { getCoverageOptions({collectCoverage: true}), ); expect(result.sourceMapPath).toEqual(expect.any(String)); - expect(writeFileAtomic.sync).toBeCalledTimes(2); + expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); expect(writeFileAtomic.sync).toBeCalledWith( result.sourceMapPath, JSON.stringify(instrumentedCodeMap), @@ -1333,7 +1333,7 @@ describe('ScriptTransformer', () => { getCoverageOptions({collectCoverage: true}), ); expect(result.sourceMapPath).toEqual(expect.any(String)); - expect(writeFileAtomic.sync).toBeCalledTimes(2); + expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); expect(writeFileAtomic.sync).toBeCalledWith( result.sourceMapPath, JSON.stringify(instrumentedCodeMap), diff --git a/packages/jest-types/__typetests__/expect.test.ts b/packages/jest-types/__typetests__/expect.test.ts index b5b98e58cd14..510624fe16f8 100644 --- a/packages/jest-types/__typetests__/expect.test.ts +++ b/packages/jest-types/__typetests__/expect.test.ts @@ -198,9 +198,9 @@ expectError(expect(jest.fn()).toHaveBeenCalled('value')); expectType(expect(jest.fn()).toHaveBeenCalled()); expectError(expect(jest.fn()).toHaveBeenCalled(false)); -expectType(expect(jest.fn()).toBeCalledTimes(1)); -expectError(expect(jest.fn()).toBeCalledTimes('twice')); -expectError(expect(jest.fn()).toBeCalledTimes()); +expectType(expect(jest.fn()).toHaveBeenCalledTimes(1)); +expectError(expect(jest.fn()).toHaveBeenCalledTimes('twice')); +expectError(expect(jest.fn()).toHaveBeenCalledTimes()); expectType(expect(jest.fn()).toHaveBeenCalledTimes(3)); expectError(expect(jest.fn()).toHaveBeenCalledTimes(true)); expectError(expect(jest.fn()).toHaveBeenCalledTimes()); diff --git a/packages/jest-worker/src/__tests__/Farm.test.js b/packages/jest-worker/src/__tests__/Farm.test.js index b8aacfe0242b..f77165d3a2d8 100644 --- a/packages/jest-worker/src/__tests__/Farm.test.js +++ b/packages/jest-worker/src/__tests__/Farm.test.js @@ -111,7 +111,7 @@ describe('Farm', () => { workerReply(0); await p0; - expect(computeWorkerKey).toBeCalledTimes(1); + expect(computeWorkerKey).toHaveBeenCalledTimes(1); expect(computeWorkerKey).toHaveBeenNthCalledWith(1, 'foo', 42); expect(callback).toHaveBeenCalledTimes(1); @@ -146,7 +146,7 @@ describe('Farm', () => { workerReply(2); await p2; - expect(computeWorkerKey).toBeCalledTimes(3); + expect(computeWorkerKey).toHaveBeenCalledTimes(3); expect(computeWorkerKey).toHaveBeenNthCalledWith(1, 'foo', 42); expect(computeWorkerKey).toHaveBeenNthCalledWith(2, 'foo1', 43); expect(computeWorkerKey).toHaveBeenNthCalledWith(3, 'foo2', 44); From f1d4a75c778ec6fd4df12c855a64df20bf0ac69a Mon Sep 17 00:00:00 2001 From: EduardoSCosta Date: Mon, 29 Aug 2022 17:23:17 -0300 Subject: [PATCH 04/13] chore: remove .toBeCalledWith() matcher --- .../__tests__/fetch_current_user.test.js | 2 +- examples/timer/__tests__/timer_game.test.js | 2 +- examples/typescript/__tests__/calc.test.ts | 8 +- .../__snapshots__/spyMatchers.test.ts.snap | 191 ------------------ .../expect/src/__tests__/spyMatchers.test.ts | 2 - packages/expect/src/spyMatchers.ts | 1 - packages/expect/src/types.ts | 4 - .../__tests__/SnapshotInteractiveMode.test.js | 6 +- .../src/__tests__/TestScheduler.test.js | 2 +- .../watchFilenamePatternMode.test.js | 2 +- .../watchTestNamePatternMode.test.js | 2 +- .../src/__tests__/sinon-integration.test.ts | 8 +- .../src/__tests__/index.test.js | 12 +- .../src/crawlers/__tests__/watchman.test.js | 4 +- .../src/__tests__/CoverageWorker.test.js | 2 +- .../src/__tests__/getResultHeader.test.js | 2 +- .../src/__tests__/Runtime-statics.test.js | 4 +- .../jest-snapshot/src/__tests__/utils.test.ts | 4 +- .../src/__tests__/ScriptTransformer.test.ts | 117 ++++++----- .../jest-types/__typetests__/expect.test.ts | 12 +- .../src/__tests__/WorkerPool.test.js | 12 +- .../__tests__/ChildProcessWorker.test.js | 2 +- .../__tests__/NodeThreadsWorker.test.js | 2 +- 23 files changed, 113 insertions(+), 290 deletions(-) diff --git a/examples/jquery/__tests__/fetch_current_user.test.js b/examples/jquery/__tests__/fetch_current_user.test.js index 0ae9287f45bd..8c1a8f66595a 100644 --- a/examples/jquery/__tests__/fetch_current_user.test.js +++ b/examples/jquery/__tests__/fetch_current_user.test.js @@ -14,7 +14,7 @@ it('calls into $.ajax with the correct params', () => { // Now make sure that $.ajax was properly called during the previous // 2 lines - expect($.ajax).toBeCalledWith({ + expect($.ajax).toHaveBeenCalledWith({ success: expect.any(Function), type: 'GET', url: 'http://example.com/currentUser', diff --git a/examples/timer/__tests__/timer_game.test.js b/examples/timer/__tests__/timer_game.test.js index c00ccc5b89ee..f54c4c115641 100644 --- a/examples/timer/__tests__/timer_game.test.js +++ b/examples/timer/__tests__/timer_game.test.js @@ -13,7 +13,7 @@ describe('timerGame', () => { timerGame(); expect(setTimeout).toHaveBeenCalledTimes(1); - expect(setTimeout).toBeCalledWith(expect.any(Function), 1000); + expect(setTimeout).toHaveBeenCalledWith(expect.any(Function), 1000); }); it('calls the callback after 1 second via runAllTimers', () => { diff --git a/examples/typescript/__tests__/calc.test.ts b/examples/typescript/__tests__/calc.test.ts index af6c36391ba0..cf60244ff37c 100644 --- a/examples/typescript/__tests__/calc.test.ts +++ b/examples/typescript/__tests__/calc.test.ts @@ -25,7 +25,7 @@ describe('calc - mocks', () => { const result = calc('Sub', [2, 2]); expect(result).toEqual(0); - expect(mockSub).toBeCalledWith(2, 2); + expect(mockSub).toHaveBeenCalledWith(2, 2); }); it('returns result from sum', () => { @@ -35,7 +35,7 @@ describe('calc - mocks', () => { const result = calc('Sum', [1, 1]); expect(result).toEqual(2); - expect(mockSum).toBeCalledWith(1, 1); + expect(mockSum).toHaveBeenCalledWith(1, 1); }); it('adds last result to memory', () => { @@ -48,7 +48,7 @@ describe('calc - mocks', () => { expect(sumResult).toEqual(2); expect(memoryResult).toEqual(2); - expect(MockMemory.prototype.add).toBeCalledWith(2); + expect(MockMemory.prototype.add).toHaveBeenCalledWith(2); }); it('subtracts last result to memory', () => { @@ -61,7 +61,7 @@ describe('calc - mocks', () => { expect(sumResult).toEqual(2); expect(memoryResult).toEqual(2); - expect(MockMemory.prototype.subtract).toBeCalledWith(2); + expect(MockMemory.prototype.subtract).toHaveBeenCalledWith(2); }); it('clears the memory', () => { diff --git a/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap b/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap index fe698dc4b1a0..1f341719aeb5 100644 --- a/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap +++ b/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap @@ -819,197 +819,6 @@ Expected: not undefined Number of returns: 1 `; -exports[`toBeCalledWith includes the custom mock name in the error message 1`] = ` -expect(named-mock).not.toBeCalledWith(...expected) - -Expected: not "foo", "bar" - -Number of calls: 1 -`; - -exports[`toBeCalledWith works only on spies or jest.fn 1`] = ` -expect(received).toBeCalledWith(...expected) - -Matcher error: received value must be a mock or spy function - -Received has type: function -Received has value: [Function fn] -`; - -exports[`toBeCalledWith works when not called 1`] = ` -expect(jest.fn()).toBeCalledWith(...expected) - -Expected: "foo", "bar" - -Number of calls: 0 -`; - -exports[`toBeCalledWith works with Immutable.js objects 1`] = ` -expect(jest.fn()).not.toBeCalledWith(...expected) - -Expected: not Immutable.Map {"a": {"b": "c"}}, Immutable.Map {"a": {"b": "c"}} - -Number of calls: 1 -`; - -exports[`toBeCalledWith works with Map 1`] = ` -expect(jest.fn()).not.toBeCalledWith(...expected) - -Expected: not Map {1 => 2, 2 => 1} - -Number of calls: 1 -`; - -exports[`toBeCalledWith works with Map 2`] = ` -expect(jest.fn()).toBeCalledWith(...expected) - -- Expected -+ Received - - Map { -- "a" => "b", -- "b" => "a", -+ 1 => 2, -+ 2 => 1, - }, - -Number of calls: 1 -`; - -exports[`toBeCalledWith works with Set 1`] = ` -expect(jest.fn()).not.toBeCalledWith(...expected) - -Expected: not Set {1, 2} - -Number of calls: 1 -`; - -exports[`toBeCalledWith works with Set 2`] = ` -expect(jest.fn()).toBeCalledWith(...expected) - -- Expected -+ Received - - Set { -- 3, -- 4, -+ 1, -+ 2, - }, - -Number of calls: 1 -`; - -exports[`toBeCalledWith works with arguments that don't match 1`] = ` -expect(jest.fn()).toBeCalledWith(...expected) - -Expected: "foo", "bar" -Received: "foo", "bar1" - -Number of calls: 1 -`; - -exports[`toBeCalledWith works with arguments that don't match in number of arguments 1`] = ` -expect(jest.fn()).toBeCalledWith(...expected) - -Expected: "foo", "bar" -Received: "foo", "bar", "plop" - -Number of calls: 1 -`; - -exports[`toBeCalledWith works with arguments that don't match in size even if one is an optional matcher 1`] = ` -expect(jest.fn()).toBeCalledWith(...expected) - -Expected: "foo", optionalFn<> -Received: "foo" - -Number of calls: 1 -`; - -exports[`toBeCalledWith works with arguments that don't match with matchers 1`] = ` -expect(jest.fn()).toBeCalledWith(...expected) - -Expected: Any, Any -Received: "foo", "bar" - -Number of calls: 1 -`; - -exports[`toBeCalledWith works with arguments that don't match with matchers even when argument is undefined 1`] = ` -expect(jest.fn()).toBeCalledWith(...expected) - -Expected: "foo", Any -Received: "foo", undefined - -Number of calls: 1 -`; - -exports[`toBeCalledWith works with arguments that match 1`] = ` -expect(jest.fn()).not.toBeCalledWith(...expected) - -Expected: not "foo", "bar" - -Number of calls: 1 -`; - -exports[`toBeCalledWith works with arguments that match with matchers 1`] = ` -expect(jest.fn()).not.toBeCalledWith(...expected) - -Expected: not Any, Any -Received: 0, ["foo", "bar"] - -Number of calls: 1 -`; - -exports[`toBeCalledWith works with many arguments 1`] = ` -expect(jest.fn()).not.toBeCalledWith(...expected) - -Expected: not "foo", "bar" -Received - 3: "foo", "bar" - -Number of calls: 3 -`; - -exports[`toBeCalledWith works with many arguments that don't match 1`] = ` -expect(jest.fn()).toBeCalledWith(...expected) - -Expected: "foo", "bar" -Received - 1: "foo", "bar1" - 2: "foo", "bar2" - 3: "foo", "bar3" - -Number of calls: 3 -`; - -exports[`toBeCalledWith works with trailing undefined arguments 1`] = ` -expect(jest.fn()).toBeCalledWith(...expected) - -Expected: "foo" -Received: "foo", undefined - -Number of calls: 1 -`; - -exports[`toBeCalledWith works with trailing undefined arguments if requested by the match query 1`] = ` -expect(jest.fn()).not.toBeCalledWith(...expected) - -Expected: not "foo", undefined - -Number of calls: 1 -`; - -exports[`toBeCalledWith works with trailing undefined arguments when explicitely requested as optional by matcher 1`] = ` -expect(jest.fn()).not.toBeCalledWith(...expected) - -Expected: not "foo", optionalFn<> -Received: 0, ["foo", undefined] - -Number of calls: 1 -`; - exports[`toHaveBeenCalled .not fails with any argument passed 1`] = ` expect(received).not.toHaveBeenCalled() diff --git a/packages/expect/src/__tests__/spyMatchers.test.ts b/packages/expect/src/__tests__/spyMatchers.test.ts index ccf29923a315..8ad4ad26d1d9 100644 --- a/packages/expect/src/__tests__/spyMatchers.test.ts +++ b/packages/expect/src/__tests__/spyMatchers.test.ts @@ -187,7 +187,6 @@ describe('toHaveBeenCalledTimes', () => { 'toHaveBeenLastCalledWith', 'nthCalledWith', 'toHaveBeenNthCalledWith', - 'toBeCalledWith', 'toHaveBeenCalledWith', ].forEach(calledWith => { const caller = function ( @@ -437,7 +436,6 @@ describe('toHaveBeenCalledTimes', () => { const basicCalledWith = [ 'lastCalledWith', 'toHaveBeenLastCalledWith', - 'toBeCalledWith', 'toHaveBeenCalledWith', ]; diff --git a/packages/expect/src/spyMatchers.ts b/packages/expect/src/spyMatchers.ts index 126ebd98afb6..2e5ce19c620e 100644 --- a/packages/expect/src/spyMatchers.ts +++ b/packages/expect/src/spyMatchers.ts @@ -1140,7 +1140,6 @@ const spyMatchers: MatchersObject = { lastReturnedWith: createLastReturnedMatcher('lastReturnedWith'), nthCalledWith: createNthCalledWithMatcher('nthCalledWith'), nthReturnedWith: createNthReturnedWithMatcher('nthReturnedWith'), - toBeCalledWith: createToBeCalledWithMatcher('toBeCalledWith'), toHaveBeenCalled: createToBeCalledMatcher('toHaveBeenCalled'), toHaveBeenCalledTimes: createToBeCalledTimesMatcher('toHaveBeenCalledTimes'), toHaveBeenCalledWith: createToBeCalledWithMatcher('toHaveBeenCalledWith'), diff --git a/packages/expect/src/types.ts b/packages/expect/src/types.ts index f1679103d4ea..2180439b621b 100644 --- a/packages/expect/src/types.ts +++ b/packages/expect/src/types.ts @@ -153,10 +153,6 @@ export interface Matchers> { * Don't use `toBe` with floating-point numbers. */ toBe(expected: unknown): R; - /** - * Ensure that a mock function is called with specific arguments. - */ - toBeCalledWith(...expected: Array): R; /** * Using exact equality with floating point numbers is a bad idea. * Rounding means that intuitive things fail. diff --git a/packages/jest-core/src/__tests__/SnapshotInteractiveMode.test.js b/packages/jest-core/src/__tests__/SnapshotInteractiveMode.test.js index 6e7135a87796..80ffd654e5e0 100644 --- a/packages/jest-core/src/__tests__/SnapshotInteractiveMode.test.js +++ b/packages/jest-core/src/__tests__/SnapshotInteractiveMode.test.js @@ -38,7 +38,7 @@ describe('SnapshotInteractiveMode', () => { ]; instance.run(assertions, mockCallback); expect(instance.isActive()).toBeTruthy(); - expect(mockCallback).toBeCalledWith(assertions[0], false); + expect(mockCallback).toHaveBeenCalledWith(assertions[0], false); }); test('call to abort', () => { @@ -51,7 +51,7 @@ describe('SnapshotInteractiveMode', () => { instance.abort(); expect(instance.isActive()).toBeFalsy(); expect(instance.getSkippedNum()).toBe(0); - expect(mockCallback).toBeCalledWith(null, false); + expect(mockCallback).toHaveBeenCalledWith(null, false); }); test('call to reset', () => { @@ -64,7 +64,7 @@ describe('SnapshotInteractiveMode', () => { instance.restart(); expect(instance.isActive()).toBeTruthy(); expect(instance.getSkippedNum()).toBe(0); - expect(mockCallback).toBeCalledWith(assertions[0], false); + expect(mockCallback).toHaveBeenCalledWith(assertions[0], false); }); test('press Q or ESC triggers an abort', () => { diff --git a/packages/jest-core/src/__tests__/TestScheduler.test.js b/packages/jest-core/src/__tests__/TestScheduler.test.js index a8c222bbb486..836fc9118121 100644 --- a/packages/jest-core/src/__tests__/TestScheduler.test.js +++ b/packages/jest-core/src/__tests__/TestScheduler.test.js @@ -312,7 +312,7 @@ test('should bail after `n` failures', async () => { snapshot: {}, testResults: [{}], }); - expect(setState).toBeCalledWith({interrupted: true}); + expect(setState).toHaveBeenCalledWith({interrupted: true}); }); test('should not bail if less than `n` failures', async () => { diff --git a/packages/jest-core/src/__tests__/watchFilenamePatternMode.test.js b/packages/jest-core/src/__tests__/watchFilenamePatternMode.test.js index b9cf687d393c..fd636625d45f 100644 --- a/packages/jest-core/src/__tests__/watchFilenamePatternMode.test.js +++ b/packages/jest-core/src/__tests__/watchFilenamePatternMode.test.js @@ -93,7 +93,7 @@ describe('Watch mode flows', () => { // Write a enter pattern mode stdin.emit('p'); - expect(pipe.write).toBeCalledWith(' pattern › '); + expect(pipe.write).toHaveBeenCalledWith(' pattern › '); const assertPattern = hex => { pipe.write.mockReset(); diff --git a/packages/jest-core/src/__tests__/watchTestNamePatternMode.test.js b/packages/jest-core/src/__tests__/watchTestNamePatternMode.test.js index 804ea50ea03d..1a8f525494ca 100644 --- a/packages/jest-core/src/__tests__/watchTestNamePatternMode.test.js +++ b/packages/jest-core/src/__tests__/watchTestNamePatternMode.test.js @@ -107,7 +107,7 @@ describe('Watch mode flows', () => { // Write a enter pattern mode stdin.emit('t'); - expect(pipe.write).toBeCalledWith(' pattern › '); + expect(pipe.write).toHaveBeenCalledWith(' pattern › '); const assertPattern = hex => { pipe.write.mockReset(); diff --git a/packages/jest-fake-timers/src/__tests__/sinon-integration.test.ts b/packages/jest-fake-timers/src/__tests__/sinon-integration.test.ts index 528e2d15937c..c845bad2568e 100644 --- a/packages/jest-fake-timers/src/__tests__/sinon-integration.test.ts +++ b/packages/jest-fake-timers/src/__tests__/sinon-integration.test.ts @@ -49,7 +49,7 @@ describe('`@sinonjs/fake-timers` integration', () => { timers.useFakeTimers(); - expect(mockInstall).toBeCalledWith({ + expect(mockInstall).toHaveBeenCalledWith({ advanceTimeDelta: undefined, loopLimit: 100_000, now: 123456, @@ -86,7 +86,7 @@ describe('`@sinonjs/fake-timers` integration', () => { timers.useFakeTimers(); - expect(mockInstall).toBeCalledWith({ + expect(mockInstall).toHaveBeenCalledWith({ advanceTimeDelta: undefined, loopLimit: 100, now: 0, @@ -119,7 +119,7 @@ describe('`@sinonjs/fake-timers` integration', () => { timerLimit: 2000, }); - expect(mockInstall).toBeCalledWith({ + expect(mockInstall).toHaveBeenCalledWith({ advanceTimeDelta: 40, loopLimit: 2000, now: new Date('1995-12-17'), @@ -158,7 +158,7 @@ describe('`@sinonjs/fake-timers` integration', () => { now: 123456, }); - expect(mockInstall).toBeCalledWith({ + expect(mockInstall).toHaveBeenCalledWith({ advanceTimeDelta: undefined, loopLimit: 1000, now: 123456, diff --git a/packages/jest-haste-map/src/__tests__/index.test.js b/packages/jest-haste-map/src/__tests__/index.test.js index 1e79945424ce..1508442eefe1 100644 --- a/packages/jest-haste-map/src/__tests__/index.test.js +++ b/packages/jest-haste-map/src/__tests__/index.test.js @@ -693,7 +693,7 @@ describe('HasteMap', () => { expect(data.map.get('IRequireAVideo')).toBeDefined(); expect(data.files.get(path.join('video', 'video.mp4'))).toBeDefined(); - expect(fs.readFileSync).not.toBeCalledWith( + expect(fs.readFileSync).not.toHaveBeenCalledWith( path.join('video', 'video.mp4'), 'utf8', ); @@ -904,9 +904,9 @@ describe('HasteMap', () => { ).build(); expect(fs.readFileSync.mock.calls.length).toBe(1); if (require('v8').deserialize) { - expect(fs.readFileSync).toBeCalledWith(cacheFilePath); + expect(fs.readFileSync).toHaveBeenCalledWith(cacheFilePath); } else { - expect(fs.readFileSync).toBeCalledWith(cacheFilePath, 'utf8'); + expect(fs.readFileSync).toHaveBeenCalledWith(cacheFilePath, 'utf8'); } expect(useBuitinsInContext(data.clocks)).toEqual(mockClocks); expect(useBuitinsInContext(data.files)).toEqual(initialData.files); @@ -939,11 +939,11 @@ describe('HasteMap', () => { expect(fs.readFileSync.mock.calls.length).toBe(2); if (require('v8').serialize) { - expect(fs.readFileSync).toBeCalledWith(cacheFilePath); + expect(fs.readFileSync).toHaveBeenCalledWith(cacheFilePath); } else { - expect(fs.readFileSync).toBeCalledWith(cacheFilePath, 'utf8'); + expect(fs.readFileSync).toHaveBeenCalledWith(cacheFilePath, 'utf8'); } - expect(fs.readFileSync).toBeCalledWith( + expect(fs.readFileSync).toHaveBeenCalledWith( path.join('/', 'project', 'fruits', 'Banana.js'), 'utf8', ); diff --git a/packages/jest-haste-map/src/crawlers/__tests__/watchman.test.js b/packages/jest-haste-map/src/crawlers/__tests__/watchman.test.js index c5ac6436bf4d..4661799ea2f1 100644 --- a/packages/jest-haste-map/src/crawlers/__tests__/watchman.test.js +++ b/packages/jest-haste-map/src/crawlers/__tests__/watchman.test.js @@ -140,7 +140,7 @@ describe('watchman watch', () => { const calls = client.command.mock.calls; expect(client.on).toHaveBeenCalled(); - expect(client.on).toBeCalledWith('error', expect.any(Function)); + expect(client.on).toHaveBeenCalledWith('error', expect.any(Function)); // Call 0 and 1 are for ['watch-project'] expect(calls[0][0][0]).toEqual('watch-project'); @@ -482,7 +482,7 @@ describe('watchman watch', () => { const calls = client.command.mock.calls; expect(client.on).toHaveBeenCalled(); - expect(client.on).toBeCalledWith('error', expect.any(Function)); + expect(client.on).toHaveBeenCalledWith('error', expect.any(Function)); // First 3 calls are for ['watch-project'] expect(calls[0][0][0]).toEqual('watch-project'); diff --git a/packages/jest-reporters/src/__tests__/CoverageWorker.test.js b/packages/jest-reporters/src/__tests__/CoverageWorker.test.js index e83b1f13287c..af7eece9a16b 100644 --- a/packages/jest-reporters/src/__tests__/CoverageWorker.test.js +++ b/packages/jest-reporters/src/__tests__/CoverageWorker.test.js @@ -36,7 +36,7 @@ test('resolves to the result of generateEmptyCoverage upon success', async () => const result = await worker(workerOptions); - expect(generateEmptyCoverage).toBeCalledWith( + expect(generateEmptyCoverage).toHaveBeenCalledWith( validJS, 'banana.js', globalConfig, diff --git a/packages/jest-reporters/src/__tests__/getResultHeader.test.js b/packages/jest-reporters/src/__tests__/getResultHeader.test.js index 845b03ed4886..9c7efb001d67 100644 --- a/packages/jest-reporters/src/__tests__/getResultHeader.test.js +++ b/packages/jest-reporters/src/__tests__/getResultHeader.test.js @@ -45,7 +45,7 @@ beforeEach(() => { test('should call `terminal-link` correctly', () => { getResultHeader(testResult, globalConfig); - expect(terminalLink).toBeCalledWith( + expect(terminalLink).toHaveBeenCalledWith( expect.stringContaining('foo'), 'file:///foo', expect.objectContaining({fallback: expect.any(Function)}), diff --git a/packages/jest-runtime/src/__tests__/Runtime-statics.test.js b/packages/jest-runtime/src/__tests__/Runtime-statics.test.js index 849e332a82f7..ee2ca1f5124a 100644 --- a/packages/jest-runtime/src/__tests__/Runtime-statics.test.js +++ b/packages/jest-runtime/src/__tests__/Runtime-statics.test.js @@ -26,7 +26,7 @@ describe('Runtime statics', () => { test('Runtime.createHasteMap passes correct ignore files to HasteMap', async () => { await Runtime.createHasteMap(projectConfig, options); - expect(HasteMap.create).toBeCalledWith( + expect(HasteMap.create).toHaveBeenCalledWith( expect.objectContaining({ ignorePattern: /\/root\/ignore-1|\/root\/ignore-2/, }), @@ -35,7 +35,7 @@ describe('Runtime statics', () => { test('Runtime.createHasteMap passes correct ignore files to HasteMap in watch mode', async () => { await Runtime.createHasteMap(projectConfig, {...options, watch: true}); - expect(HasteMap.create).toBeCalledWith( + expect(HasteMap.create).toHaveBeenCalledWith( expect.objectContaining({ ignorePattern: /\/root\/ignore-1|\/root\/ignore-2|\/watch-root\/ignore-1/, diff --git a/packages/jest-snapshot/src/__tests__/utils.test.ts b/packages/jest-snapshot/src/__tests__/utils.test.ts index 853db21e4172..7d6cc062e03e 100644 --- a/packages/jest-snapshot/src/__tests__/utils.test.ts +++ b/packages/jest-snapshot/src/__tests__/utils.test.ts @@ -49,7 +49,7 @@ test('saveSnapshotFile() works with \r\n', () => { }; saveSnapshotFile(data, filename); - expect(fs.writeFileSync).toBeCalledWith( + expect(fs.writeFileSync).toHaveBeenCalledWith( filename, `// Jest Snapshot v1, ${SNAPSHOT_GUIDE_LINK}\n\n` + 'exports[`myKey`] = `
\n
`;\n', @@ -63,7 +63,7 @@ test('saveSnapshotFile() works with \r', () => { }; saveSnapshotFile(data, filename); - expect(fs.writeFileSync).toBeCalledWith( + expect(fs.writeFileSync).toHaveBeenCalledWith( filename, `// Jest Snapshot v1, ${SNAPSHOT_GUIDE_LINK}\n\n` + 'exports[`myKey`] = `
\n
`;\n', diff --git a/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts b/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts index cb8a82b9ecb5..6d3e381bdd8e 100644 --- a/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts +++ b/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts @@ -301,7 +301,7 @@ describe('ScriptTransformer', () => { // no-cache case expect(fs.readFileSync).toHaveBeenCalledTimes(1); - expect(fs.readFileSync).toBeCalledWith('/fruits/banana.js', 'utf8'); + expect(fs.readFileSync).toHaveBeenCalledWith('/fruits/banana.js', 'utf8'); // in-memory cache const transformedBananaWithCoverageAgain = scriptTransformer.transform( @@ -346,7 +346,7 @@ describe('ScriptTransformer', () => { // no-cache case expect(fs.readFileSync).toHaveBeenCalledTimes(1); - expect(fs.readFileSync).toBeCalledWith('/fruits/banana.js', 'utf8'); + expect(fs.readFileSync).toHaveBeenCalledWith('/fruits/banana.js', 'utf8'); // in-memory cache const transformedBananaWithCoverageAgain = @@ -708,10 +708,14 @@ describe('ScriptTransformer', () => { expect(result.sourceMapPath).toEqual(expect.any(String)); const mapStr = JSON.stringify(map); expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); - expect(writeFileAtomic.sync).toBeCalledWith(result.sourceMapPath, mapStr, { - encoding: 'utf8', - fsync: false, - }); + expect(writeFileAtomic.sync).toHaveBeenCalledWith( + result.sourceMapPath, + mapStr, + { + encoding: 'utf8', + fsync: false, + }, + ); }); it('in async mode, writes source map if preprocessor supplies it', async () => { @@ -738,10 +742,14 @@ describe('ScriptTransformer', () => { expect(result.sourceMapPath).toEqual(expect.any(String)); const mapStr = JSON.stringify(map); expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); - expect(writeFileAtomic.sync).toBeCalledWith(result.sourceMapPath, mapStr, { - encoding: 'utf8', - fsync: false, - }); + expect(writeFileAtomic.sync).toHaveBeenCalledWith( + result.sourceMapPath, + mapStr, + { + encoding: 'utf8', + fsync: false, + }, + ); }); it('in async mode, writes source map if async preprocessor supplies it', async () => { @@ -770,10 +778,14 @@ describe('ScriptTransformer', () => { expect(result.sourceMapPath).toEqual(expect.any(String)); const mapStr = JSON.stringify(map); expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); - expect(writeFileAtomic.sync).toBeCalledWith(result.sourceMapPath, mapStr, { - encoding: 'utf8', - fsync: false, - }); + expect(writeFileAtomic.sync).toHaveBeenCalledWith( + result.sourceMapPath, + mapStr, + { + encoding: 'utf8', + fsync: false, + }, + ); }); it('writes source map if preprocessor inlines it', async () => { @@ -804,7 +816,7 @@ describe('ScriptTransformer', () => { ); expect(result.sourceMapPath).toEqual(expect.any(String)); expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); - expect(writeFileAtomic.sync).toBeCalledWith( + expect(writeFileAtomic.sync).toHaveBeenCalledWith( result.sourceMapPath, sourceMap, {encoding: 'utf8', fsync: false}, @@ -839,7 +851,7 @@ describe('ScriptTransformer', () => { ); expect(result.sourceMapPath).toEqual(expect.any(String)); expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); - expect(writeFileAtomic.sync).toBeCalledWith( + expect(writeFileAtomic.sync).toHaveBeenCalledWith( result.sourceMapPath, sourceMap, {encoding: 'utf8', fsync: false}, @@ -874,7 +886,7 @@ describe('ScriptTransformer', () => { ); expect(result.sourceMapPath).toEqual(expect.any(String)); expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); - expect(writeFileAtomic.sync).toBeCalledWith( + expect(writeFileAtomic.sync).toHaveBeenCalledWith( result.sourceMapPath, sourceMap, {encoding: 'utf8', fsync: false}, @@ -1025,7 +1037,7 @@ describe('ScriptTransformer', () => { ); expect(result.sourceMapPath).toEqual(expect.any(String)); expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); - expect(writeFileAtomic.sync).toBeCalledWith( + expect(writeFileAtomic.sync).toHaveBeenCalledWith( result.sourceMapPath, JSON.stringify(map), { @@ -1132,7 +1144,7 @@ describe('ScriptTransformer', () => { ); expect(result.sourceMapPath).toEqual(expect.any(String)); expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); - expect(writeFileAtomic.sync).toBeCalledWith( + expect(writeFileAtomic.sync).toHaveBeenCalledWith( result.sourceMapPath, JSON.stringify(instrumentedCodeMap), expect.anything(), @@ -1177,7 +1189,7 @@ describe('ScriptTransformer', () => { ); expect(result.sourceMapPath).toEqual(expect.any(String)); expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); - expect(writeFileAtomic.sync).toBeCalledWith( + expect(writeFileAtomic.sync).toHaveBeenCalledWith( result.sourceMapPath, JSON.stringify(instrumentedCodeMap), expect.anything(), @@ -1224,7 +1236,7 @@ describe('ScriptTransformer', () => { ); expect(result.sourceMapPath).toEqual(expect.any(String)); expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); - expect(writeFileAtomic.sync).toBeCalledWith( + expect(writeFileAtomic.sync).toHaveBeenCalledWith( result.sourceMapPath, JSON.stringify(instrumentedCodeMap), expect.anything(), @@ -1260,7 +1272,7 @@ describe('ScriptTransformer', () => { ); expect(result.sourceMapPath).toEqual(expect.any(String)); expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); - expect(writeFileAtomic.sync).toBeCalledWith( + expect(writeFileAtomic.sync).toHaveBeenCalledWith( result.sourceMapPath, JSON.stringify(instrumentedCodeMap), expect.anything(), @@ -1296,7 +1308,7 @@ describe('ScriptTransformer', () => { ); expect(result.sourceMapPath).toEqual(expect.any(String)); expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); - expect(writeFileAtomic.sync).toBeCalledWith( + expect(writeFileAtomic.sync).toHaveBeenCalledWith( result.sourceMapPath, JSON.stringify(instrumentedCodeMap), expect.anything(), @@ -1334,7 +1346,7 @@ describe('ScriptTransformer', () => { ); expect(result.sourceMapPath).toEqual(expect.any(String)); expect(writeFileAtomic.sync).toHaveBeenCalledTimes(2); - expect(writeFileAtomic.sync).toBeCalledWith( + expect(writeFileAtomic.sync).toHaveBeenCalledWith( result.sourceMapPath, JSON.stringify(instrumentedCodeMap), expect.anything(), @@ -1430,8 +1442,8 @@ describe('ScriptTransformer', () => { scriptTransformer.transform('/fruits/banana.js', getCoverageOptions()); expect(fs.readFileSync).toHaveBeenCalledTimes(2); - expect(fs.readFileSync).toBeCalledWith('/fruits/banana.js', 'utf8'); - expect(fs.readFileSync).toBeCalledWith(cachePath, 'utf8'); + expect(fs.readFileSync).toHaveBeenCalledWith('/fruits/banana.js', 'utf8'); + expect(fs.readFileSync).toHaveBeenCalledWith(cachePath, 'utf8'); expect(writeFileAtomic.sync).not.toHaveBeenCalled(); // Don't read from the cache when `config.cache` is false. @@ -1443,8 +1455,8 @@ describe('ScriptTransformer', () => { scriptTransformer.transform('/fruits/banana.js', getCoverageOptions()); expect(fs.readFileSync).toHaveBeenCalledTimes(1); - expect(fs.readFileSync).toBeCalledWith('/fruits/banana.js', 'utf8'); - expect(fs.readFileSync).not.toBeCalledWith(cachePath, 'utf8'); + expect(fs.readFileSync).toHaveBeenCalledWith('/fruits/banana.js', 'utf8'); + expect(fs.readFileSync).not.toHaveBeenCalledWith(cachePath, 'utf8'); expect(writeFileAtomic.sync).toHaveBeenCalled(); }); @@ -1477,8 +1489,8 @@ describe('ScriptTransformer', () => { ); expect(fs.readFileSync).toHaveBeenCalledTimes(2); - expect(fs.readFileSync).toBeCalledWith('/fruits/banana.js', 'utf8'); - expect(fs.readFileSync).toBeCalledWith(cachePath, 'utf8'); + expect(fs.readFileSync).toHaveBeenCalledWith('/fruits/banana.js', 'utf8'); + expect(fs.readFileSync).toHaveBeenCalledWith(cachePath, 'utf8'); expect(writeFileAtomic.sync).not.toHaveBeenCalled(); // Don't read from the cache when `config.cache` is false. @@ -1493,8 +1505,8 @@ describe('ScriptTransformer', () => { ); expect(fs.readFileSync).toHaveBeenCalledTimes(1); - expect(fs.readFileSync).toBeCalledWith('/fruits/banana.js', 'utf8'); - expect(fs.readFileSync).not.toBeCalledWith(cachePath, 'utf8'); + expect(fs.readFileSync).toHaveBeenCalledWith('/fruits/banana.js', 'utf8'); + expect(fs.readFileSync).not.toHaveBeenCalledWith(cachePath, 'utf8'); expect(writeFileAtomic.sync).toHaveBeenCalled(); }); @@ -1527,8 +1539,8 @@ describe('ScriptTransformer', () => { ); expect(fs.readFileSync).toHaveBeenCalledTimes(2); - expect(fs.readFileSync).toBeCalledWith('/fruits/banana.js', 'utf8'); - expect(fs.readFileSync).toBeCalledWith(cachePath, 'utf8'); + expect(fs.readFileSync).toHaveBeenCalledWith('/fruits/banana.js', 'utf8'); + expect(fs.readFileSync).toHaveBeenCalledWith(cachePath, 'utf8'); expect(writeFileAtomic.sync).not.toHaveBeenCalled(); // Don't read from the cache when `config.cache` is false. @@ -1543,8 +1555,8 @@ describe('ScriptTransformer', () => { ); expect(fs.readFileSync).toHaveBeenCalledTimes(1); - expect(fs.readFileSync).toBeCalledWith('/fruits/banana.js', 'utf8'); - expect(fs.readFileSync).not.toBeCalledWith(cachePath, 'utf8'); + expect(fs.readFileSync).toHaveBeenCalledWith('/fruits/banana.js', 'utf8'); + expect(fs.readFileSync).not.toHaveBeenCalledWith(cachePath, 'utf8'); expect(writeFileAtomic.sync).toHaveBeenCalled(); }); @@ -1574,8 +1586,11 @@ describe('ScriptTransformer', () => { scriptTransformer.transform('/fruits/banana:colon.js', {}); expect(fs.readFileSync).toHaveBeenCalledTimes(2); - expect(fs.readFileSync).toBeCalledWith('/fruits/banana:colon.js', 'utf8'); - expect(fs.readFileSync).toBeCalledWith(cachePath, 'utf8'); + expect(fs.readFileSync).toHaveBeenCalledWith( + '/fruits/banana:colon.js', + 'utf8', + ); + expect(fs.readFileSync).toHaveBeenCalledWith(cachePath, 'utf8'); expect(writeFileAtomic.sync).not.toHaveBeenCalled(); }); @@ -1605,8 +1620,11 @@ describe('ScriptTransformer', () => { await scriptTransformer.transformAsync('/fruits/banana:colon.js', {}); expect(fs.readFileSync).toHaveBeenCalledTimes(2); - expect(fs.readFileSync).toBeCalledWith('/fruits/banana:colon.js', 'utf8'); - expect(fs.readFileSync).toBeCalledWith(cachePath, 'utf8'); + expect(fs.readFileSync).toHaveBeenCalledWith( + '/fruits/banana:colon.js', + 'utf8', + ); + expect(fs.readFileSync).toHaveBeenCalledWith(cachePath, 'utf8'); expect(writeFileAtomic.sync).not.toHaveBeenCalled(); }); @@ -1636,8 +1654,11 @@ describe('ScriptTransformer', () => { await scriptTransformer.transformAsync('/fruits/banana:colon.js', {}); expect(fs.readFileSync).toHaveBeenCalledTimes(2); - expect(fs.readFileSync).toBeCalledWith('/fruits/banana:colon.js', 'utf8'); - expect(fs.readFileSync).toBeCalledWith(cachePath, 'utf8'); + expect(fs.readFileSync).toHaveBeenCalledWith( + '/fruits/banana:colon.js', + 'utf8', + ); + expect(fs.readFileSync).toHaveBeenCalledWith(cachePath, 'utf8'); expect(writeFileAtomic.sync).not.toHaveBeenCalled(); }); @@ -1663,7 +1684,7 @@ describe('ScriptTransformer', () => { expect(testPreprocessor.getCacheKey.mock.calls[0][2].cacheFS).toBeDefined(); expect(testPreprocessor.process.mock.calls[0][2].cacheFS).toBeDefined(); expect(fs.readFileSync).toHaveBeenCalledTimes(1); - expect(fs.readFileSync).toBeCalledWith(fileName1, 'utf8'); + expect(fs.readFileSync).toHaveBeenCalledWith(fileName1, 'utf8'); }); it('in async mode, should reuse the value from in-memory cache which is set by custom preprocessor', async () => { @@ -1688,7 +1709,7 @@ describe('ScriptTransformer', () => { expect(testPreprocessor.getCacheKey.mock.calls[0][2].cacheFS).toBeDefined(); expect(testPreprocessor.process.mock.calls[0][2].cacheFS).toBeDefined(); expect(fs.readFileSync).toHaveBeenCalledTimes(1); - expect(fs.readFileSync).toBeCalledWith(fileName1, 'utf8'); + expect(fs.readFileSync).toHaveBeenCalledWith(fileName1, 'utf8'); }); it('should reuse the value from in-memory cache which is set by custom async preprocessor', async () => { @@ -1717,7 +1738,7 @@ describe('ScriptTransformer', () => { testPreprocessor.processAsync.mock.calls[0][2].cacheFS, ).toBeDefined(); expect(fs.readFileSync).toHaveBeenCalledTimes(1); - expect(fs.readFileSync).toBeCalledWith(fileName1, 'utf8'); + expect(fs.readFileSync).toHaveBeenCalledWith(fileName1, 'utf8'); }); it('does not reuse the in-memory cache between different projects', async () => { @@ -1739,7 +1760,7 @@ describe('ScriptTransformer', () => { ); expect(fs.readFileSync).toHaveBeenCalledTimes(2); - expect(fs.readFileSync).toBeCalledWith('/fruits/banana.js', 'utf8'); + expect(fs.readFileSync).toHaveBeenCalledWith('/fruits/banana.js', 'utf8'); }); it('async mode does not reuse the in-memory cache between different projects', async () => { @@ -1764,7 +1785,7 @@ describe('ScriptTransformer', () => { ); expect(fs.readFileSync).toHaveBeenCalledTimes(2); - expect(fs.readFileSync).toBeCalledWith('/fruits/banana.js', 'utf8'); + expect(fs.readFileSync).toHaveBeenCalledWith('/fruits/banana.js', 'utf8'); }); it('regardless of sync/async, does not reuse the in-memory cache between different projects', async () => { @@ -1804,7 +1825,7 @@ describe('ScriptTransformer', () => { ); expect(fs.readFileSync).toHaveBeenCalledTimes(4); - expect(fs.readFileSync).toBeCalledWith('/fruits/banana.js', 'utf8'); + expect(fs.readFileSync).toHaveBeenCalledWith('/fruits/banana.js', 'utf8'); }); it('preload transformer when using `createScriptTransformer`', async () => { diff --git a/packages/jest-types/__typetests__/expect.test.ts b/packages/jest-types/__typetests__/expect.test.ts index 510624fe16f8..857e98e092d3 100644 --- a/packages/jest-types/__typetests__/expect.test.ts +++ b/packages/jest-types/__typetests__/expect.test.ts @@ -16,9 +16,9 @@ expectType(expect('value').toEqual(expect.any(String))); expectError(expect(123).toEqual(expect.any())); expectError(expect('value').toEqual(expect.not.any(Number))); -expectType(expect(jest.fn()).toBeCalledWith(expect.anything())); -expectError(expect(jest.fn()).toBeCalledWith(expect.anything(true))); -expectError(expect(jest.fn()).toBeCalledWith(expect.not.anything())); +expectType(expect(jest.fn()).toHaveBeenCalledWith(expect.anything())); +expectError(expect(jest.fn()).toHaveBeenCalledWith(expect.anything(true))); +expectError(expect(jest.fn()).toHaveBeenCalledWith(expect.not.anything())); expectType(expect(['A', 'B']).toEqual(expect.arrayContaining(['A']))); expectError(expect(['A']).toEqual(expect.arrayContaining('A'))); @@ -205,9 +205,9 @@ expectType(expect(jest.fn()).toHaveBeenCalledTimes(3)); expectError(expect(jest.fn()).toHaveBeenCalledTimes(true)); expectError(expect(jest.fn()).toHaveBeenCalledTimes()); -expectType(expect(jest.fn()).toBeCalledWith()); -expectType(expect(jest.fn()).toBeCalledWith('value')); -expectType(expect(jest.fn()).toBeCalledWith('value', 123)); +expectType(expect(jest.fn()).toHaveBeenCalledWith()); +expectType(expect(jest.fn()).toHaveBeenCalledWith('value')); +expectType(expect(jest.fn()).toHaveBeenCalledWith('value', 123)); expectType(expect(jest.fn()).toHaveBeenCalledWith()); expectType(expect(jest.fn()).toHaveBeenCalledWith(123)); expectType(expect(jest.fn()).toHaveBeenCalledWith(123, 'value')); diff --git a/packages/jest-worker/src/__tests__/WorkerPool.test.js b/packages/jest-worker/src/__tests__/WorkerPool.test.js index 8945c5d9d4ce..1134eda510a6 100644 --- a/packages/jest-worker/src/__tests__/WorkerPool.test.js +++ b/packages/jest-worker/src/__tests__/WorkerPool.test.js @@ -57,14 +57,14 @@ describe('WorkerPool', () => { const onEnd = () => {}; workerPool.send(0, {foo: 'bar'}, onStart, onEnd); - expect(ChildProcessWorker).toBeCalledWith({ + expect(ChildProcessWorker).toHaveBeenCalledWith({ forkOptions: {}, maxRetries: 1, workerId: 0, workerPath: '/path', }); expect(NodeThreadWorker).not.toHaveBeenCalled(); - expect(workerPool._workers[0].send).toBeCalledWith( + expect(workerPool._workers[0].send).toHaveBeenCalledWith( {foo: 'bar'}, onStart, onEnd, @@ -87,14 +87,14 @@ describe('WorkerPool', () => { const onEnd = () => {}; workerPool.send(0, {foo: 'bar'}, onStart, onEnd); - expect(NodeThreadWorker).toBeCalledWith({ + expect(NodeThreadWorker).toHaveBeenCalledWith({ forkOptions: {}, maxRetries: 1, workerId: 0, workerPath: '/path', }); expect(ChildProcessWorker).not.toHaveBeenCalled(); - expect(workerPool._workers[0].send).toBeCalledWith( + expect(workerPool._workers[0].send).toHaveBeenCalledWith( {foo: 'bar'}, onStart, onEnd, @@ -116,14 +116,14 @@ describe('WorkerPool', () => { const onEnd = () => {}; workerPool.send(0, {foo: 'bar'}, onStart, onEnd); - expect(ChildProcessWorker).toBeCalledWith({ + expect(ChildProcessWorker).toHaveBeenCalledWith({ forkOptions: {}, maxRetries: 1, workerId: 0, workerPath: '/path', }); expect(NodeThreadWorker).not.toHaveBeenCalled(); - expect(workerPool._workers[0].send).toBeCalledWith( + expect(workerPool._workers[0].send).toHaveBeenCalledWith( {foo: 'bar'}, onStart, onEnd, diff --git a/packages/jest-worker/src/workers/__tests__/ChildProcessWorker.test.js b/packages/jest-worker/src/workers/__tests__/ChildProcessWorker.test.js index bce2d97a3bea..42375a6935ba 100644 --- a/packages/jest-worker/src/workers/__tests__/ChildProcessWorker.test.js +++ b/packages/jest-worker/src/workers/__tests__/ChildProcessWorker.test.js @@ -137,7 +137,7 @@ it('stops initializing the worker after the amount of retries is exceeded', () = forkInterface.emit('exit', 1); expect(childProcess.fork).toHaveBeenCalledTimes(5); - expect(onProcessStart).toBeCalledWith(worker); + expect(onProcessStart).toHaveBeenCalledWith(worker); expect(onProcessEnd).toHaveBeenCalledTimes(1); expect(onProcessEnd.mock.calls[0][0]).toBeInstanceOf(Error); expect(onProcessEnd.mock.calls[0][0].type).toBe('WorkerError'); diff --git a/packages/jest-worker/src/workers/__tests__/NodeThreadsWorker.test.js b/packages/jest-worker/src/workers/__tests__/NodeThreadsWorker.test.js index e522f44ffff6..698b587caeec 100644 --- a/packages/jest-worker/src/workers/__tests__/NodeThreadsWorker.test.js +++ b/packages/jest-worker/src/workers/__tests__/NodeThreadsWorker.test.js @@ -121,7 +121,7 @@ it('stops initializing the worker after the amount of retries is exceeded', () = worker._worker.emit('exit'); expect(workerThreads).toHaveBeenCalledTimes(5); - expect(onProcessStart).toBeCalledWith(worker); + expect(onProcessStart).toHaveBeenCalledWith(worker); expect(onProcessEnd).toHaveBeenCalledTimes(1); expect(onProcessEnd.mock.calls[0][0]).toBeInstanceOf(Error); expect(onProcessEnd.mock.calls[0][0].type).toBe('WorkerError'); From 8f39d3f91e85f79e4cad70624fffd268673e7b86 Mon Sep 17 00:00:00 2001 From: EduardoSCosta Date: Mon, 29 Aug 2022 17:43:35 -0300 Subject: [PATCH 05/13] chore: remove .lastCalledWith() matcher --- .../__snapshots__/spyMatchers.test.ts.snap | 191 ------------------ .../expect/src/__tests__/spyMatchers.test.ts | 2 - packages/expect/src/spyMatchers.ts | 1 - packages/expect/src/types.ts | 4 - .../src/crawlers/__tests__/node.test.js | 4 +- .../jest-types/__typetests__/expect.test.ts | 13 +- 6 files changed, 5 insertions(+), 210 deletions(-) diff --git a/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap b/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap index 1f341719aeb5..bfacc4fd7595 100644 --- a/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap +++ b/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap @@ -1,196 +1,5 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`lastCalledWith includes the custom mock name in the error message 1`] = ` -expect(named-mock).not.lastCalledWith(...expected) - -Expected: not "foo", "bar" - -Number of calls: 1 -`; - -exports[`lastCalledWith works only on spies or jest.fn 1`] = ` -expect(received).lastCalledWith(...expected) - -Matcher error: received value must be a mock or spy function - -Received has type: function -Received has value: [Function fn] -`; - -exports[`lastCalledWith works when not called 1`] = ` -expect(jest.fn()).lastCalledWith(...expected) - -Expected: "foo", "bar" - -Number of calls: 0 -`; - -exports[`lastCalledWith works with Immutable.js objects 1`] = ` -expect(jest.fn()).not.lastCalledWith(...expected) - -Expected: not Immutable.Map {"a": {"b": "c"}}, Immutable.Map {"a": {"b": "c"}} - -Number of calls: 1 -`; - -exports[`lastCalledWith works with Map 1`] = ` -expect(jest.fn()).not.lastCalledWith(...expected) - -Expected: not Map {1 => 2, 2 => 1} - -Number of calls: 1 -`; - -exports[`lastCalledWith works with Map 2`] = ` -expect(jest.fn()).lastCalledWith(...expected) - -- Expected -+ Received - - Map { -- "a" => "b", -- "b" => "a", -+ 1 => 2, -+ 2 => 1, - }, - -Number of calls: 1 -`; - -exports[`lastCalledWith works with Set 1`] = ` -expect(jest.fn()).not.lastCalledWith(...expected) - -Expected: not Set {1, 2} - -Number of calls: 1 -`; - -exports[`lastCalledWith works with Set 2`] = ` -expect(jest.fn()).lastCalledWith(...expected) - -- Expected -+ Received - - Set { -- 3, -- 4, -+ 1, -+ 2, - }, - -Number of calls: 1 -`; - -exports[`lastCalledWith works with arguments that don't match 1`] = ` -expect(jest.fn()).lastCalledWith(...expected) - -Expected: "foo", "bar" -Received: "foo", "bar1" - -Number of calls: 1 -`; - -exports[`lastCalledWith works with arguments that don't match in number of arguments 1`] = ` -expect(jest.fn()).lastCalledWith(...expected) - -Expected: "foo", "bar" -Received: "foo", "bar", "plop" - -Number of calls: 1 -`; - -exports[`lastCalledWith works with arguments that don't match in size even if one is an optional matcher 1`] = ` -expect(jest.fn()).lastCalledWith(...expected) - -Expected: "foo", optionalFn<> -Received: "foo" - -Number of calls: 1 -`; - -exports[`lastCalledWith works with arguments that don't match with matchers 1`] = ` -expect(jest.fn()).lastCalledWith(...expected) - -Expected: Any, Any -Received: "foo", "bar" - -Number of calls: 1 -`; - -exports[`lastCalledWith works with arguments that don't match with matchers even when argument is undefined 1`] = ` -expect(jest.fn()).lastCalledWith(...expected) - -Expected: "foo", Any -Received: "foo", undefined - -Number of calls: 1 -`; - -exports[`lastCalledWith works with arguments that match 1`] = ` -expect(jest.fn()).not.lastCalledWith(...expected) - -Expected: not "foo", "bar" - -Number of calls: 1 -`; - -exports[`lastCalledWith works with arguments that match with matchers 1`] = ` -expect(jest.fn()).not.lastCalledWith(...expected) - -Expected: not Any, Any -Received: 0, ["foo", "bar"] - -Number of calls: 1 -`; - -exports[`lastCalledWith works with many arguments 1`] = ` -expect(jest.fn()).not.lastCalledWith(...expected) - -Expected: not "foo", "bar" -Received - 2: "foo", "bar1" --> 3: "foo", "bar" - -Number of calls: 3 -`; - -exports[`lastCalledWith works with many arguments that don't match 1`] = ` -expect(jest.fn()).lastCalledWith(...expected) - -Expected: "foo", "bar" -Received - 2: "foo", "bar2" --> 3: "foo", "bar3" - -Number of calls: 3 -`; - -exports[`lastCalledWith works with trailing undefined arguments 1`] = ` -expect(jest.fn()).lastCalledWith(...expected) - -Expected: "foo" -Received: "foo", undefined - -Number of calls: 1 -`; - -exports[`lastCalledWith works with trailing undefined arguments if requested by the match query 1`] = ` -expect(jest.fn()).not.lastCalledWith(...expected) - -Expected: not "foo", undefined - -Number of calls: 1 -`; - -exports[`lastCalledWith works with trailing undefined arguments when explicitely requested as optional by matcher 1`] = ` -expect(jest.fn()).not.lastCalledWith(...expected) - -Expected: not "foo", optionalFn<> -Received: 0, ["foo", undefined] - -Number of calls: 1 -`; - exports[`lastReturnedWith a call that throws is not considered to have returned 1`] = ` expect(jest.fn()).lastReturnedWith(expected) diff --git a/packages/expect/src/__tests__/spyMatchers.test.ts b/packages/expect/src/__tests__/spyMatchers.test.ts index 8ad4ad26d1d9..24f5e676fe24 100644 --- a/packages/expect/src/__tests__/spyMatchers.test.ts +++ b/packages/expect/src/__tests__/spyMatchers.test.ts @@ -183,7 +183,6 @@ describe('toHaveBeenCalledTimes', () => { }); [ - 'lastCalledWith', 'toHaveBeenLastCalledWith', 'nthCalledWith', 'toHaveBeenNthCalledWith', @@ -434,7 +433,6 @@ describe('toHaveBeenCalledTimes', () => { }); const basicCalledWith = [ - 'lastCalledWith', 'toHaveBeenLastCalledWith', 'toHaveBeenCalledWith', ]; diff --git a/packages/expect/src/spyMatchers.ts b/packages/expect/src/spyMatchers.ts index 2e5ce19c620e..41aa9843b8ab 100644 --- a/packages/expect/src/spyMatchers.ts +++ b/packages/expect/src/spyMatchers.ts @@ -1136,7 +1136,6 @@ const createNthReturnedWithMatcher = (matcherName: string) => }; const spyMatchers: MatchersObject = { - lastCalledWith: createLastCalledWithMatcher('lastCalledWith'), lastReturnedWith: createLastReturnedMatcher('lastReturnedWith'), nthCalledWith: createNthCalledWithMatcher('nthCalledWith'), nthReturnedWith: createNthReturnedWithMatcher('nthReturnedWith'), diff --git a/packages/expect/src/types.ts b/packages/expect/src/types.ts index 2180439b621b..b3b2da029297 100644 --- a/packages/expect/src/types.ts +++ b/packages/expect/src/types.ts @@ -132,10 +132,6 @@ type PromiseMatchers = { }; export interface Matchers> { - /** - * Ensures the last call to a mock function was provided specific args. - */ - lastCalledWith(...expected: Array): R; /** * Ensure that the last call to a mock function has returned a specified value. */ diff --git a/packages/jest-haste-map/src/crawlers/__tests__/node.test.js b/packages/jest-haste-map/src/crawlers/__tests__/node.test.js index 0f34ca33e5dc..f8b6b0147b67 100644 --- a/packages/jest-haste-map/src/crawlers/__tests__/node.test.js +++ b/packages/jest-haste-map/src/crawlers/__tests__/node.test.js @@ -159,7 +159,7 @@ describe('node crawler', () => { roots: ['/project/fruits', '/project/vegetables'], }); - expect(childProcess.spawn).lastCalledWith('find', [ + expect(childProcess.spawn).toHaveBeenLastCalledWith('find', [ '/project/fruits', '/project/vegetables', '-type', @@ -266,7 +266,7 @@ describe('node crawler', () => { roots: ['/project/fruits'], }); - expect(childProcess.spawn).lastCalledWith( + expect(childProcess.spawn).toHaveBeenLastCalledWith( 'find', ['.', '-type', 'f', '(', '-iname', '*.ts', '-o', '-iname', '*.js', ')'], {cwd: expect.any(String)}, diff --git a/packages/jest-types/__typetests__/expect.test.ts b/packages/jest-types/__typetests__/expect.test.ts index 857e98e092d3..1c8e1a6a1196 100644 --- a/packages/jest-types/__typetests__/expect.test.ts +++ b/packages/jest-types/__typetests__/expect.test.ts @@ -195,28 +195,21 @@ expectType(expect(() => {}).toThrow(new Error('error'))); expectType(expect(jest.fn()).toHaveBeenCalled()); expectError(expect(jest.fn()).toHaveBeenCalled('value')); -expectType(expect(jest.fn()).toHaveBeenCalled()); expectError(expect(jest.fn()).toHaveBeenCalled(false)); -expectType(expect(jest.fn()).toHaveBeenCalledTimes(1)); -expectError(expect(jest.fn()).toHaveBeenCalledTimes('twice')); expectError(expect(jest.fn()).toHaveBeenCalledTimes()); expectType(expect(jest.fn()).toHaveBeenCalledTimes(3)); +expectError(expect(jest.fn()).toHaveBeenCalledTimes('twice')); expectError(expect(jest.fn()).toHaveBeenCalledTimes(true)); -expectError(expect(jest.fn()).toHaveBeenCalledTimes()); -expectType(expect(jest.fn()).toHaveBeenCalledWith()); -expectType(expect(jest.fn()).toHaveBeenCalledWith('value')); -expectType(expect(jest.fn()).toHaveBeenCalledWith('value', 123)); expectType(expect(jest.fn()).toHaveBeenCalledWith()); expectType(expect(jest.fn()).toHaveBeenCalledWith(123)); +expectType(expect(jest.fn()).toHaveBeenCalledWith('value')); expectType(expect(jest.fn()).toHaveBeenCalledWith(123, 'value')); -expectType(expect(jest.fn()).lastCalledWith()); -expectType(expect(jest.fn()).lastCalledWith('value')); -expectType(expect(jest.fn()).lastCalledWith('value', 123)); expectType(expect(jest.fn()).toHaveBeenLastCalledWith()); expectType(expect(jest.fn()).toHaveBeenLastCalledWith(123)); +expectType(expect(jest.fn()).toHaveBeenLastCalledWith('value')); expectType(expect(jest.fn()).toHaveBeenLastCalledWith(123, 'value')); expectType(expect(jest.fn()).nthCalledWith(2)); From c46b16cceb2ef7ab2002189858913be8091f870f Mon Sep 17 00:00:00 2001 From: EduardoSCosta Date: Mon, 29 Aug 2022 18:04:16 -0300 Subject: [PATCH 06/13] chore: remove .nthCalledWith() matcher --- .../__snapshots__/spyMatchers.test.ts.snap | 225 ------------------ .../expect/src/__tests__/spyMatchers.test.ts | 10 +- packages/expect/src/spyMatchers.ts | 1 - packages/expect/src/types.ts | 4 - .../__tests__/SnapshotInteractiveMode.test.js | 46 ++-- .../src/__tests__/testRunner.test.ts | 4 +- .../jest-types/__typetests__/expect.test.ts | 4 - 7 files changed, 28 insertions(+), 266 deletions(-) diff --git a/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap b/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap index bfacc4fd7595..be6c36e7bbfd 100644 --- a/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap +++ b/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap @@ -143,231 +143,6 @@ Expected: not undefined Number of returns: 1 `; -exports[`nthCalledWith includes the custom mock name in the error message 1`] = ` -expect(named-mock).not.nthCalledWith(n, ...expected) - -n: 1 -Expected: not "foo", "bar" - -Number of calls: 1 -`; - -exports[`nthCalledWith negative throw matcher error for n that is not integer 1`] = ` -expect(received).not.nthCalledWith(n, ...expected) - -Matcher error: n must be a positive integer - -n has type: number -n has value: Infinity -`; - -exports[`nthCalledWith positive throw matcher error for n that is not integer 1`] = ` -expect(received).nthCalledWith(n, ...expected) - -Matcher error: n must be a positive integer - -n has type: number -n has value: 0.1 -`; - -exports[`nthCalledWith positive throw matcher error for n that is not positive integer 1`] = ` -expect(received).nthCalledWith(n, ...expected) - -Matcher error: n must be a positive integer - -n has type: number -n has value: 0 -`; - -exports[`nthCalledWith works only on spies or jest.fn 1`] = ` -expect(received).nthCalledWith(n, ...expected) - -Matcher error: received value must be a mock or spy function - -Received has type: function -Received has value: [Function fn] -`; - -exports[`nthCalledWith works when not called 1`] = ` -expect(jest.fn()).nthCalledWith(n, ...expected) - -n: 1 -Expected: "foo", "bar" - -Number of calls: 0 -`; - -exports[`nthCalledWith works with Immutable.js objects 1`] = ` -expect(jest.fn()).not.nthCalledWith(n, ...expected) - -n: 1 -Expected: not Immutable.Map {"a": {"b": "c"}}, Immutable.Map {"a": {"b": "c"}} - -Number of calls: 1 -`; - -exports[`nthCalledWith works with Map 1`] = ` -expect(jest.fn()).not.nthCalledWith(n, ...expected) - -n: 1 -Expected: not Map {1 => 2, 2 => 1} - -Number of calls: 1 -`; - -exports[`nthCalledWith works with Map 2`] = ` -expect(jest.fn()).nthCalledWith(n, ...expected) - -n: 1 -- Expected -+ Received - - Map { -- "a" => "b", -- "b" => "a", -+ 1 => 2, -+ 2 => 1, - }, - -Number of calls: 1 -`; - -exports[`nthCalledWith works with Set 1`] = ` -expect(jest.fn()).not.nthCalledWith(n, ...expected) - -n: 1 -Expected: not Set {1, 2} - -Number of calls: 1 -`; - -exports[`nthCalledWith works with Set 2`] = ` -expect(jest.fn()).nthCalledWith(n, ...expected) - -n: 1 -- Expected -+ Received - - Set { -- 3, -- 4, -+ 1, -+ 2, - }, - -Number of calls: 1 -`; - -exports[`nthCalledWith works with arguments that don't match 1`] = ` -expect(jest.fn()).nthCalledWith(n, ...expected) - -n: 1 -Expected: "foo", "bar" -Received: "foo", "bar1" - -Number of calls: 1 -`; - -exports[`nthCalledWith works with arguments that don't match in number of arguments 1`] = ` -expect(jest.fn()).nthCalledWith(n, ...expected) - -n: 1 -Expected: "foo", "bar" -Received: "foo", "bar", "plop" - -Number of calls: 1 -`; - -exports[`nthCalledWith works with arguments that don't match in size even if one is an optional matcher 1`] = ` -expect(jest.fn()).nthCalledWith(n, ...expected) - -n: 1 -Expected: "foo", optionalFn<> -Received: "foo" - -Number of calls: 1 -`; - -exports[`nthCalledWith works with arguments that don't match with matchers 1`] = ` -expect(jest.fn()).nthCalledWith(n, ...expected) - -n: 1 -Expected: Any, Any -Received: "foo", "bar" - -Number of calls: 1 -`; - -exports[`nthCalledWith works with arguments that don't match with matchers even when argument is undefined 1`] = ` -expect(jest.fn()).nthCalledWith(n, ...expected) - -n: 1 -Expected: "foo", Any -Received: "foo", undefined - -Number of calls: 1 -`; - -exports[`nthCalledWith works with arguments that match 1`] = ` -expect(jest.fn()).not.nthCalledWith(n, ...expected) - -n: 1 -Expected: not "foo", "bar" - -Number of calls: 1 -`; - -exports[`nthCalledWith works with arguments that match with matchers 1`] = ` -expect(jest.fn()).not.nthCalledWith(n, ...expected) - -n: 1 -Expected: not Any, Any -Received: 0, ["foo", "bar"] - -Number of calls: 1 -`; - -exports[`nthCalledWith works with three calls 1`] = ` -expect(jest.fn()).not.nthCalledWith(n, ...expected) - -n: 1 -Expected: not "foo1", "bar" -Received --> 1: "foo1", "bar" - 2: "foo", "bar1" - -Number of calls: 3 -`; - -exports[`nthCalledWith works with trailing undefined arguments 1`] = ` -expect(jest.fn()).nthCalledWith(n, ...expected) - -n: 1 -Expected: "foo" -Received: "foo", undefined - -Number of calls: 1 -`; - -exports[`nthCalledWith works with trailing undefined arguments if requested by the match query 1`] = ` -expect(jest.fn()).not.nthCalledWith(n, ...expected) - -n: 1 -Expected: not "foo", undefined - -Number of calls: 1 -`; - -exports[`nthCalledWith works with trailing undefined arguments when explicitely requested as optional by matcher 1`] = ` -expect(jest.fn()).not.nthCalledWith(n, ...expected) - -n: 1 -Expected: not "foo", optionalFn<> -Received: 0, ["foo", undefined] - -Number of calls: 1 -`; - exports[`nthReturnedWith a call that throws is not considered to have returned 1`] = ` expect(jest.fn()).nthReturnedWith(n, expected) diff --git a/packages/expect/src/__tests__/spyMatchers.test.ts b/packages/expect/src/__tests__/spyMatchers.test.ts index 24f5e676fe24..7fb73f99021f 100644 --- a/packages/expect/src/__tests__/spyMatchers.test.ts +++ b/packages/expect/src/__tests__/spyMatchers.test.ts @@ -184,7 +184,6 @@ describe('toHaveBeenCalledTimes', () => { [ 'toHaveBeenLastCalledWith', - 'nthCalledWith', 'toHaveBeenNthCalledWith', 'toHaveBeenCalledWith', ].forEach(calledWith => { @@ -192,15 +191,13 @@ describe('toHaveBeenCalledTimes', () => { callee: (...a: Array) => void, ...args: Array ) { - if ( - calledWith === 'nthCalledWith' || - calledWith === 'toHaveBeenNthCalledWith' - ) { + if (calledWith === 'toHaveBeenNthCalledWith') { callee(1, ...args); } else { callee(...args); } }; + describe(`${calledWith}`, () => { test('works only on spies or jest.fn', () => { const fn = function fn() {}; @@ -465,8 +462,7 @@ describe('toHaveBeenCalledTimes', () => { }); } - const nthCalled = ['toHaveBeenNthCalledWith', 'nthCalledWith']; - if (nthCalled.indexOf(calledWith) >= 0) { + if (calledWith === 'toHaveBeenNthCalledWith') { test('works with three calls', () => { const fn = jest.fn(); fn('foo1', 'bar'); diff --git a/packages/expect/src/spyMatchers.ts b/packages/expect/src/spyMatchers.ts index 41aa9843b8ab..4ccb0964d367 100644 --- a/packages/expect/src/spyMatchers.ts +++ b/packages/expect/src/spyMatchers.ts @@ -1137,7 +1137,6 @@ const createNthReturnedWithMatcher = (matcherName: string) => const spyMatchers: MatchersObject = { lastReturnedWith: createLastReturnedMatcher('lastReturnedWith'), - nthCalledWith: createNthCalledWithMatcher('nthCalledWith'), nthReturnedWith: createNthReturnedWithMatcher('nthReturnedWith'), toHaveBeenCalled: createToBeCalledMatcher('toHaveBeenCalled'), toHaveBeenCalledTimes: createToBeCalledTimesMatcher('toHaveBeenCalledTimes'), diff --git a/packages/expect/src/types.ts b/packages/expect/src/types.ts index b3b2da029297..1439e3f5bc76 100644 --- a/packages/expect/src/types.ts +++ b/packages/expect/src/types.ts @@ -136,10 +136,6 @@ export interface Matchers> { * Ensure that the last call to a mock function has returned a specified value. */ lastReturnedWith(expected: unknown): R; - /** - * Ensure that a mock function is called with specific arguments on an Nth call. - */ - nthCalledWith(nth: number, ...expected: Array): R; /** * Ensure that the nth call to a mock function has returned a specified value. */ diff --git a/packages/jest-core/src/__tests__/SnapshotInteractiveMode.test.js b/packages/jest-core/src/__tests__/SnapshotInteractiveMode.test.js index 80ffd654e5e0..c9f2f8d0ef0f 100644 --- a/packages/jest-core/src/__tests__/SnapshotInteractiveMode.test.js +++ b/packages/jest-core/src/__tests__/SnapshotInteractiveMode.test.js @@ -86,7 +86,7 @@ describe('SnapshotInteractiveMode', () => { const assertions = [{fullName: 'test one', path: 'first.js'}]; instance.run(assertions, mockCallback); - expect(mockCallback).nthCalledWith(1, assertions[0], false); + expect(mockCallback).toHaveBeenNthCalledWith(1, assertions[0], false); expect(pipe.write.mock.calls.join('\n')).toMatchSnapshot(); pipe.write.mockClear(); @@ -97,7 +97,7 @@ describe('SnapshotInteractiveMode', () => { instance.put('r'); expect(instance.getSkippedNum()).toBe(0); - expect(mockCallback).nthCalledWith(2, assertions[0], false); + expect(mockCallback).toHaveBeenNthCalledWith(2, assertions[0], false); expect(mockCallback).toHaveBeenCalledTimes(2); expect(pipe.write.mock.calls.join('\n')).toMatchSnapshot(); }); @@ -106,7 +106,7 @@ describe('SnapshotInteractiveMode', () => { const assertions = [{fullName: 'test one', path: 'first.js'}]; instance.run(assertions, mockCallback); - expect(mockCallback).nthCalledWith(1, assertions[0], false); + expect(mockCallback).toHaveBeenNthCalledWith(1, assertions[0], false); expect(pipe.write.mock.calls.join('\n')).toMatchSnapshot(); pipe.write.mockClear(); @@ -117,7 +117,7 @@ describe('SnapshotInteractiveMode', () => { instance.put('q'); expect(instance.getSkippedNum()).toBe(0); - expect(mockCallback).nthCalledWith(2, null, false); + expect(mockCallback).toHaveBeenNthCalledWith(2, null, false); expect(mockCallback).toHaveBeenCalledTimes(2); }); @@ -136,18 +136,18 @@ describe('SnapshotInteractiveMode', () => { const assertions = [{fullName: 'test one', path: 'first.js'}]; instance.run(assertions, mockCallback); - expect(mockCallback).nthCalledWith(1, assertions[0], false); + expect(mockCallback).toHaveBeenNthCalledWith(1, assertions[0], false); expect(pipe.write.mock.calls.join('\n')).toMatchSnapshot(); pipe.write.mockClear(); instance.put('u'); - expect(mockCallback).nthCalledWith(2, assertions[0], true); + expect(mockCallback).toHaveBeenNthCalledWith(2, assertions[0], true); expect(mockCallback).toHaveBeenCalledTimes(2); expect(pipe.write.mock.calls.join('\n')).toMatchSnapshot(); instance.put(KEYS.ENTER); expect(instance.isActive()).toBe(false); - expect(mockCallback).nthCalledWith(3, null, false); + expect(mockCallback).toHaveBeenNthCalledWith(3, null, false); }); test('skip 2 tests, then finish and restart', () => { @@ -156,12 +156,12 @@ describe('SnapshotInteractiveMode', () => { {fullName: 'test two', path: 'first.js'}, ]; instance.run(assertions, mockCallback); - expect(mockCallback).nthCalledWith(1, assertions[0], false); + expect(mockCallback).toHaveBeenNthCalledWith(1, assertions[0], false); expect(pipe.write.mock.calls.join('\n')).toMatchSnapshot(); pipe.write.mockClear(); instance.put('s'); - expect(mockCallback).nthCalledWith(2, assertions[1], false); + expect(mockCallback).toHaveBeenNthCalledWith(2, assertions[1], false); expect(mockCallback).toHaveBeenCalledTimes(2); expect(pipe.write.mock.calls.join('\n')).toMatchSnapshot(); pipe.write.mockClear(); @@ -173,7 +173,7 @@ describe('SnapshotInteractiveMode', () => { instance.put('r'); expect(instance.getSkippedNum()).toBe(0); - expect(mockCallback).nthCalledWith(3, assertions[0], false); + expect(mockCallback).toHaveBeenNthCalledWith(3, assertions[0], false); expect(mockCallback).toHaveBeenCalledTimes(3); expect(pipe.write.mock.calls.join('\n')).toMatchSnapshot(); }); @@ -202,27 +202,27 @@ describe('SnapshotInteractiveMode', () => { ]; instance.run(assertions, mockCallback); - expect(mockCallback).nthCalledWith(1, assertions[0], false); + expect(mockCallback).toHaveBeenNthCalledWith(1, assertions[0], false); expect(mockCallback).toHaveBeenCalledTimes(1); expect(pipe.write.mock.calls.join('\n')).toMatchSnapshot(); pipe.write.mockClear(); instance.put('u'); - expect(mockCallback).nthCalledWith(2, assertions[0], true); - expect(mockCallback).nthCalledWith(3, assertions[1], false); + expect(mockCallback).toHaveBeenNthCalledWith(2, assertions[0], true); + expect(mockCallback).toHaveBeenNthCalledWith(3, assertions[1], false); expect(mockCallback).toHaveBeenCalledTimes(3); expect(pipe.write.mock.calls.join('\n')).toMatchSnapshot(); pipe.write.mockClear(); instance.put('u'); - expect(mockCallback).nthCalledWith(4, assertions[1], true); + expect(mockCallback).toHaveBeenNthCalledWith(4, assertions[1], true); expect(mockCallback).toHaveBeenCalledTimes(4); expect(pipe.write.mock.calls.join('\n')).toMatchSnapshot(); pipe.write.mockClear(); instance.put(KEYS.ENTER); expect(instance.isActive()).toBe(false); - expect(mockCallback).nthCalledWith(5, null, false); + expect(mockCallback).toHaveBeenNthCalledWith(5, null, false); expect(mockCallback).toHaveBeenCalledTimes(5); }); @@ -250,14 +250,14 @@ describe('SnapshotInteractiveMode', () => { ]; instance.run(assertions, mockCallback); - expect(mockCallback).nthCalledWith(1, assertions[0], false); + expect(mockCallback).toHaveBeenNthCalledWith(1, assertions[0], false); expect(mockCallback).toHaveBeenCalledTimes(1); expect(pipe.write.mock.calls.join('\n')).toMatchSnapshot(); pipe.write.mockClear(); instance.put('u'); - expect(mockCallback).nthCalledWith(2, assertions[0], true); - expect(mockCallback).nthCalledWith(3, assertions[1], false); + expect(mockCallback).toHaveBeenNthCalledWith(2, assertions[0], true); + expect(mockCallback).toHaveBeenNthCalledWith(3, assertions[1], false); expect(mockCallback).toHaveBeenCalledTimes(3); expect(pipe.write.mock.calls.join('\n')).toMatchSnapshot(); pipe.write.mockClear(); @@ -269,7 +269,7 @@ describe('SnapshotInteractiveMode', () => { instance.put('r'); expect(instance.getSkippedNum()).toBe(0); - expect(mockCallback).nthCalledWith(4, assertions[1], false); + expect(mockCallback).toHaveBeenNthCalledWith(4, assertions[1], false); expect(mockCallback).toHaveBeenCalledTimes(4); expect(pipe.write.mock.calls.join('\n')).toMatchSnapshot(); }); @@ -298,26 +298,26 @@ describe('SnapshotInteractiveMode', () => { ]; instance.run(assertions, mockCallback); - expect(mockCallback).nthCalledWith(1, assertions[0], false); + expect(mockCallback).toHaveBeenNthCalledWith(1, assertions[0], false); expect(mockCallback).toHaveBeenCalledTimes(1); expect(pipe.write.mock.calls.join('\n')).toMatchSnapshot(); pipe.write.mockClear(); instance.put('s'); - expect(mockCallback).nthCalledWith(2, assertions[1], false); + expect(mockCallback).toHaveBeenNthCalledWith(2, assertions[1], false); expect(mockCallback).toHaveBeenCalledTimes(2); expect(pipe.write.mock.calls.join('\n')).toMatchSnapshot(); pipe.write.mockClear(); instance.put('u'); - expect(mockCallback).nthCalledWith(3, assertions[1], true); + expect(mockCallback).toHaveBeenNthCalledWith(3, assertions[1], true); expect(mockCallback).toHaveBeenCalledTimes(3); expect(pipe.write.mock.calls.join('\n')).toMatchSnapshot(); pipe.write.mockClear(); instance.put('r'); expect(instance.getSkippedNum()).toBe(0); - expect(mockCallback).nthCalledWith(4, assertions[0], false); + expect(mockCallback).toHaveBeenNthCalledWith(4, assertions[0], false); expect(mockCallback).toHaveBeenCalledTimes(4); expect(pipe.write.mock.calls.join('\n')).toMatchSnapshot(); }); diff --git a/packages/jest-runner/src/__tests__/testRunner.test.ts b/packages/jest-runner/src/__tests__/testRunner.test.ts index fe2a53706b6f..5d60f6511955 100644 --- a/packages/jest-runner/src/__tests__/testRunner.test.ts +++ b/packages/jest-runner/src/__tests__/testRunner.test.ts @@ -47,14 +47,14 @@ test('injects the serializable module map into each worker in watch mode', async expect(mockWorkerFarm.worker).toHaveBeenCalledTimes(2); - expect(mockWorkerFarm.worker).nthCalledWith(1, { + expect(mockWorkerFarm.worker).toHaveBeenNthCalledWith(1, { config, context: runContext, globalConfig, path: './file.test.js', }); - expect(mockWorkerFarm.worker).nthCalledWith(2, { + expect(mockWorkerFarm.worker).toHaveBeenNthCalledWith(2, { config, context: runContext, globalConfig, diff --git a/packages/jest-types/__typetests__/expect.test.ts b/packages/jest-types/__typetests__/expect.test.ts index 1c8e1a6a1196..d5a106372ff5 100644 --- a/packages/jest-types/__typetests__/expect.test.ts +++ b/packages/jest-types/__typetests__/expect.test.ts @@ -212,10 +212,6 @@ expectType(expect(jest.fn()).toHaveBeenLastCalledWith(123)); expectType(expect(jest.fn()).toHaveBeenLastCalledWith('value')); expectType(expect(jest.fn()).toHaveBeenLastCalledWith(123, 'value')); -expectType(expect(jest.fn()).nthCalledWith(2)); -expectType(expect(jest.fn()).nthCalledWith(1, 'value')); -expectType(expect(jest.fn()).nthCalledWith(1, 'value', 123)); -expectError(expect(jest.fn()).nthCalledWith()); expectType(expect(jest.fn()).toHaveBeenNthCalledWith(2)); expectType(expect(jest.fn()).toHaveBeenNthCalledWith(1, 'value')); expectType(expect(jest.fn()).toHaveBeenNthCalledWith(1, 'value', 123)); From 664492c679e1e3cc5a3df34efacc34cfafb075e5 Mon Sep 17 00:00:00 2001 From: EduardoSCosta Date: Mon, 29 Aug 2022 18:15:19 -0300 Subject: [PATCH 07/13] chore: remove .toReturn() matcher --- .../__snapshots__/spyMatchers.test.ts.snap | 106 -------- .../expect/src/__tests__/spyMatchers.test.ts | 242 +++++++++--------- packages/expect/src/spyMatchers.ts | 1 - packages/expect/src/types.ts | 4 - .../jest-types/__typetests__/expect.test.ts | 3 +- 5 files changed, 125 insertions(+), 231 deletions(-) diff --git a/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap b/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap index be6c36e7bbfd..ccfe4ad83bfd 100644 --- a/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap +++ b/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap @@ -2034,112 +2034,6 @@ Expected: not undefined Number of returns: 1 `; -exports[`toReturn .not fails with any argument passed 1`] = ` -expect(received).not.toReturn() - -Matcher error: this matcher must not have an expected argument - -Expected has type: number -Expected has value: 555 -`; - -exports[`toReturn .not passes when a call throws undefined 1`] = ` -expect(jest.fn()).toReturn() - -Expected number of returns: >= 1 -Received number of returns: 0 -Received number of calls: 1 -`; - -exports[`toReturn .not passes when all calls throw 1`] = ` -expect(jest.fn()).toReturn() - -Expected number of returns: >= 1 -Received number of returns: 0 -Received number of calls: 2 -`; - -exports[`toReturn .not passes when not returned 1`] = ` -expect(jest.fn()).toReturn() - -Expected number of returns: >= 1 -Received number of returns: 0 -`; - -exports[`toReturn .not works only on jest.fn 1`] = ` -expect(received).not.toReturn() - -Matcher error: received value must be a mock function - -Received has type: function -Received has value: [Function fn] -`; - -exports[`toReturn fails with any argument passed 1`] = ` -expect(received).toReturn() - -Matcher error: this matcher must not have an expected argument - -Expected has type: number -Expected has value: 555 -`; - -exports[`toReturn includes the custom mock name in the error message 1`] = ` -expect(named-mock).not.toReturn() - -Expected number of returns: 0 -Received number of returns: 1 - -1: 42 -`; - -exports[`toReturn incomplete recursive calls are handled properly 1`] = ` -expect(jest.fn()).toReturn() - -Expected number of returns: >= 1 -Received number of returns: 0 -Received number of calls: 4 -`; - -exports[`toReturn passes when at least one call does not throw 1`] = ` -expect(jest.fn()).not.toReturn() - -Expected number of returns: 0 -Received number of returns: 2 - -1: 42 -3: 42 - -Received number of calls: 3 -`; - -exports[`toReturn passes when returned 1`] = ` -expect(jest.fn()).not.toReturn() - -Expected number of returns: 0 -Received number of returns: 1 - -1: 42 -`; - -exports[`toReturn passes when undefined is returned 1`] = ` -expect(jest.fn()).not.toReturn() - -Expected number of returns: 0 -Received number of returns: 1 - -1: undefined -`; - -exports[`toReturn throw matcher error if received is spy 1`] = ` -expect(received).toReturn() - -Matcher error: received value must be a mock function - -Received has type: function -Received has value: [Function spy] -`; - exports[`toReturnTimes .not only accepts a number argument 1`] = ` expect(received).not.toReturnTimes(expected) diff --git a/packages/expect/src/__tests__/spyMatchers.test.ts b/packages/expect/src/__tests__/spyMatchers.test.ts index 7fb73f99021f..c8e86d647947 100644 --- a/packages/expect/src/__tests__/spyMatchers.test.ts +++ b/packages/expect/src/__tests__/spyMatchers.test.ts @@ -519,153 +519,159 @@ describe('toHaveBeenCalledTimes', () => { }); }); -['toReturn', 'toHaveReturned'].forEach(returned => { - describe(`${returned}`, () => { - test('.not works only on jest.fn', () => { - const fn = function fn() {}; +describe('toHaveReturned', () => { + test('.not works only on jest.fn', () => { + const fn = function fn() {}; - expect(() => - jestExpect(fn).not[returned](), - ).toThrowErrorMatchingSnapshot(); - }); + expect(() => + jestExpect(fn).not.toHaveReturned(), + ).toThrowErrorMatchingSnapshot(); + }); - test('throw matcher error if received is spy', () => { - const spy = createSpy(jest.fn()); + test('throw matcher error if received is spy', () => { + const spy = createSpy(jest.fn()); - expect(() => jestExpect(spy)[returned]()).toThrowErrorMatchingSnapshot(); - }); + expect(() => + jestExpect(spy).toHaveReturned(), + ).toThrowErrorMatchingSnapshot(); + }); - test('passes when returned', () => { - const fn = jest.fn(() => 42); - fn(); - jestExpect(fn)[returned](); - expect(() => - jestExpect(fn).not[returned](), - ).toThrowErrorMatchingSnapshot(); - }); + test('passes when returned', () => { + const fn = jest.fn(() => 42); + fn(); + jestExpect(fn).toHaveReturned(); + expect(() => + jestExpect(fn).not.toHaveReturned(), + ).toThrowErrorMatchingSnapshot(); + }); - test('passes when undefined is returned', () => { - const fn = jest.fn(() => undefined); - fn(); - jestExpect(fn)[returned](); - expect(() => - jestExpect(fn).not[returned](), - ).toThrowErrorMatchingSnapshot(); - }); + test('passes when undefined is returned', () => { + const fn = jest.fn(() => undefined); + fn(); + jestExpect(fn).toHaveReturned(); + expect(() => + jestExpect(fn).not.toHaveReturned(), + ).toThrowErrorMatchingSnapshot(); + }); - test('passes when at least one call does not throw', () => { - const fn = jest.fn(causeError => { - if (causeError) { - throw new Error('Error!'); - } + test('passes when at least one call does not throw', () => { + const fn = jest.fn(causeError => { + if (causeError) { + throw new Error('Error!'); + } - return 42; - }); + return 42; + }); - fn(false); + fn(false); - try { - fn(true); - } catch { - // ignore error - } + try { + fn(true); + } catch { + // ignore error + } - fn(false); + fn(false); - jestExpect(fn)[returned](); - expect(() => - jestExpect(fn).not[returned](), - ).toThrowErrorMatchingSnapshot(); - }); + jestExpect(fn).toHaveReturned(); + expect(() => + jestExpect(fn).not.toHaveReturned(), + ).toThrowErrorMatchingSnapshot(); + }); - test('.not passes when not returned', () => { - const fn = jest.fn(); + test('.not passes when not returned', () => { + const fn = jest.fn(); - jestExpect(fn).not[returned](); - expect(() => jestExpect(fn)[returned]()).toThrowErrorMatchingSnapshot(); + jestExpect(fn).not.toHaveReturned(); + expect(() => + jestExpect(fn).toHaveReturned(), + ).toThrowErrorMatchingSnapshot(); + }); + + test('.not passes when all calls throw', () => { + const fn = jest.fn(() => { + throw new Error('Error!'); }); - test('.not passes when all calls throw', () => { - const fn = jest.fn(() => { - throw new Error('Error!'); - }); + try { + fn(); + } catch { + // ignore error + } - try { - fn(); - } catch { - // ignore error - } + try { + fn(); + } catch { + // ignore error + } - try { - fn(); - } catch { - // ignore error - } + jestExpect(fn).not.toHaveReturned(); + expect(() => + jestExpect(fn).toHaveReturned(), + ).toThrowErrorMatchingSnapshot(); + }); - jestExpect(fn).not[returned](); - expect(() => jestExpect(fn)[returned]()).toThrowErrorMatchingSnapshot(); + test('.not passes when a call throws undefined', () => { + const fn = jest.fn(() => { + // eslint-disable-next-line no-throw-literal + throw undefined; }); - test('.not passes when a call throws undefined', () => { - const fn = jest.fn(() => { - // eslint-disable-next-line no-throw-literal - throw undefined; - }); + try { + fn(); + } catch { + // ignore error + } - try { - fn(); - } catch { - // ignore error - } + jestExpect(fn).not.toHaveReturned(); + expect(() => + jestExpect(fn).toHaveReturned(), + ).toThrowErrorMatchingSnapshot(); + }); - jestExpect(fn).not[returned](); - expect(() => jestExpect(fn)[returned]()).toThrowErrorMatchingSnapshot(); - }); + test('fails with any argument passed', () => { + const fn = jest.fn(); - test('fails with any argument passed', () => { - const fn = jest.fn(); + fn(); + expect(() => + jestExpect(fn).toHaveReturned(555), + ).toThrowErrorMatchingSnapshot(); + }); - fn(); - expect(() => - jestExpect(fn)[returned](555), - ).toThrowErrorMatchingSnapshot(); - }); + test('.not fails with any argument passed', () => { + const fn = jest.fn(); - test('.not fails with any argument passed', () => { - const fn = jest.fn(); + expect(() => + jestExpect(fn).not.toHaveReturned(555), + ).toThrowErrorMatchingSnapshot(); + }); - expect(() => - jestExpect(fn).not[returned](555), - ).toThrowErrorMatchingSnapshot(); - }); + test('includes the custom mock name in the error message', () => { + const fn = jest.fn(() => 42).mockName('named-mock'); + fn(); + jestExpect(fn).toHaveReturned(); + expect(() => + jestExpect(fn).not.toHaveReturned(), + ).toThrowErrorMatchingSnapshot(); + }); - test('includes the custom mock name in the error message', () => { - const fn = jest.fn(() => 42).mockName('named-mock'); - fn(); - jestExpect(fn)[returned](); - expect(() => - jestExpect(fn).not[returned](), - ).toThrowErrorMatchingSnapshot(); + test('incomplete recursive calls are handled properly', () => { + // sums up all integers from 0 -> value, using recursion + const fn: jest.Mock = jest.fn(value => { + if (value === 0) { + // Before returning from the base case of recursion, none of the + // calls have returned yet. + jestExpect(fn).not.toHaveReturned(); + expect(() => + jestExpect(fn).toHaveReturned(), + ).toThrowErrorMatchingSnapshot(); + return 0; + } else { + return value + fn(value - 1); + } }); - test('incomplete recursive calls are handled properly', () => { - // sums up all integers from 0 -> value, using recursion - const fn: jest.Mock = jest.fn(value => { - if (value === 0) { - // Before returning from the base case of recursion, none of the - // calls have returned yet. - jestExpect(fn).not[returned](); - expect(() => - jestExpect(fn)[returned](), - ).toThrowErrorMatchingSnapshot(); - return 0; - } else { - return value + fn(value - 1); - } - }); - - fn(3); - }); + fn(3); }); }); diff --git a/packages/expect/src/spyMatchers.ts b/packages/expect/src/spyMatchers.ts index 4ccb0964d367..24f10991df56 100644 --- a/packages/expect/src/spyMatchers.ts +++ b/packages/expect/src/spyMatchers.ts @@ -1152,7 +1152,6 @@ const spyMatchers: MatchersObject = { toHaveReturned: createToReturnMatcher('toHaveReturned'), toHaveReturnedTimes: createToReturnTimesMatcher('toHaveReturnedTimes'), toHaveReturnedWith: createToReturnWithMatcher('toHaveReturnedWith'), - toReturn: createToReturnMatcher('toReturn'), toReturnTimes: createToReturnTimesMatcher('toReturnTimes'), toReturnWith: createToReturnWithMatcher('toReturnWith'), }; diff --git a/packages/expect/src/types.ts b/packages/expect/src/types.ts index 1439e3f5bc76..7285143d8598 100644 --- a/packages/expect/src/types.ts +++ b/packages/expect/src/types.ts @@ -294,10 +294,6 @@ export interface Matchers> { toMatchObject( expected: Record | Array>, ): R; - /** - * Ensure that a mock function has returned (as opposed to thrown) at least once. - */ - toReturn(): R; /** * Ensure that a mock function has returned (as opposed to thrown) a specified number of times. */ diff --git a/packages/jest-types/__typetests__/expect.test.ts b/packages/jest-types/__typetests__/expect.test.ts index d5a106372ff5..2c5973300631 100644 --- a/packages/jest-types/__typetests__/expect.test.ts +++ b/packages/jest-types/__typetests__/expect.test.ts @@ -217,9 +217,8 @@ expectType(expect(jest.fn()).toHaveBeenNthCalledWith(1, 'value')); expectType(expect(jest.fn()).toHaveBeenNthCalledWith(1, 'value', 123)); expectError(expect(jest.fn()).toHaveBeenNthCalledWith()); -expectType(expect(jest.fn()).toReturn()); -expectError(expect(jest.fn()).toReturn('value')); expectType(expect(jest.fn()).toHaveReturned()); +expectError(expect(jest.fn()).toHaveReturned('value')); expectError(expect(jest.fn()).toHaveReturned(false)); expectType(expect(jest.fn()).toReturnTimes(1)); From 7fc2ec97fef036e645fc66915f30de69348de7e3 Mon Sep 17 00:00:00 2001 From: EduardoSCosta Date: Mon, 29 Aug 2022 18:26:52 -0300 Subject: [PATCH 08/13] chore: remove .toReturnTimes() matcher --- .../__snapshots__/spyMatchers.test.ts.snap | 174 ------------ .../expect/src/__tests__/spyMatchers.test.ts | 254 +++++++++--------- packages/expect/src/spyMatchers.ts | 1 - packages/expect/src/types.ts | 4 - .../jest-types/__typetests__/expect.test.ts | 6 +- 5 files changed, 128 insertions(+), 311 deletions(-) diff --git a/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap b/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap index ccfe4ad83bfd..c3650820fe94 100644 --- a/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap +++ b/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap @@ -2034,180 +2034,6 @@ Expected: not undefined Number of returns: 1 `; -exports[`toReturnTimes .not only accepts a number argument 1`] = ` -expect(received).not.toReturnTimes(expected) - -Matcher error: expected value must be a non-negative integer - -Expected has type: object -Expected has value: {} -`; - -exports[`toReturnTimes .not only accepts a number argument 2`] = ` -expect(received).not.toReturnTimes(expected) - -Matcher error: expected value must be a non-negative integer - -Expected has type: array -Expected has value: [] -`; - -exports[`toReturnTimes .not only accepts a number argument 3`] = ` -expect(received).not.toReturnTimes(expected) - -Matcher error: expected value must be a non-negative integer - -Expected has type: boolean -Expected has value: true -`; - -exports[`toReturnTimes .not only accepts a number argument 4`] = ` -expect(received).not.toReturnTimes(expected) - -Matcher error: expected value must be a non-negative integer - -Expected has type: string -Expected has value: "a" -`; - -exports[`toReturnTimes .not only accepts a number argument 5`] = ` -expect(received).not.toReturnTimes(expected) - -Matcher error: expected value must be a non-negative integer - -Expected has type: map -Expected has value: Map {} -`; - -exports[`toReturnTimes .not only accepts a number argument 6`] = ` -expect(received).not.toReturnTimes(expected) - -Matcher error: expected value must be a non-negative integer - -Expected has type: function -Expected has value: [Function anonymous] -`; - -exports[`toReturnTimes .not passes if function called less than expected times 1`] = ` -expect(jest.fn()).toReturnTimes(expected) - -Expected number of returns: 2 -Received number of returns: 1 -`; - -exports[`toReturnTimes .not passes if function returned more than expected times 1`] = ` -expect(jest.fn()).toReturnTimes(expected) - -Expected number of returns: 2 -Received number of returns: 3 -`; - -exports[`toReturnTimes calls that return undefined are counted as returns 1`] = ` -expect(jest.fn()).not.toReturnTimes(expected) - -Expected number of returns: not 2 -`; - -exports[`toReturnTimes calls that throw are not counted 1`] = ` -expect(jest.fn()).toReturnTimes(expected) - -Expected number of returns: 3 -Received number of returns: 2 -Received number of calls: 3 -`; - -exports[`toReturnTimes calls that throw undefined are not counted 1`] = ` -expect(jest.fn()).not.toReturnTimes(expected) - -Expected number of returns: not 2 - -Received number of calls: 3 -`; - -exports[`toReturnTimes includes the custom mock name in the error message 1`] = ` -expect(named-mock).toReturnTimes(expected) - -Expected number of returns: 1 -Received number of returns: 2 -`; - -exports[`toReturnTimes incomplete recursive calls are handled properly 1`] = ` -expect(jest.fn()).not.toReturnTimes(expected) - -Expected number of returns: not 2 - -Received number of calls: 4 -`; - -exports[`toReturnTimes only accepts a number argument 1`] = ` -expect(received).toReturnTimes(expected) - -Matcher error: expected value must be a non-negative integer - -Expected has type: object -Expected has value: {} -`; - -exports[`toReturnTimes only accepts a number argument 2`] = ` -expect(received).toReturnTimes(expected) - -Matcher error: expected value must be a non-negative integer - -Expected has type: array -Expected has value: [] -`; - -exports[`toReturnTimes only accepts a number argument 3`] = ` -expect(received).toReturnTimes(expected) - -Matcher error: expected value must be a non-negative integer - -Expected has type: boolean -Expected has value: true -`; - -exports[`toReturnTimes only accepts a number argument 4`] = ` -expect(received).toReturnTimes(expected) - -Matcher error: expected value must be a non-negative integer - -Expected has type: string -Expected has value: "a" -`; - -exports[`toReturnTimes only accepts a number argument 5`] = ` -expect(received).toReturnTimes(expected) - -Matcher error: expected value must be a non-negative integer - -Expected has type: map -Expected has value: Map {} -`; - -exports[`toReturnTimes only accepts a number argument 6`] = ` -expect(received).toReturnTimes(expected) - -Matcher error: expected value must be a non-negative integer - -Expected has type: function -Expected has value: [Function anonymous] -`; - -exports[`toReturnTimes passes if function returned equal to expected times 1`] = ` -expect(jest.fn()).not.toReturnTimes(expected) - -Expected number of returns: not 2 -`; - -exports[`toReturnTimes throw matcher error if received is spy 1`] = ` -expect(received).not.toReturnTimes(expected) - -Matcher error: received value must be a mock function - -Received has type: function -Received has value: [Function spy] -`; - exports[`toReturnWith a call that throws is not considered to have returned 1`] = ` expect(jest.fn()).toReturnWith(expected) diff --git a/packages/expect/src/__tests__/spyMatchers.test.ts b/packages/expect/src/__tests__/spyMatchers.test.ts index c8e86d647947..e914ee121f2f 100644 --- a/packages/expect/src/__tests__/spyMatchers.test.ts +++ b/packages/expect/src/__tests__/spyMatchers.test.ts @@ -675,176 +675,174 @@ describe('toHaveReturned', () => { }); }); -['toReturnTimes', 'toHaveReturnedTimes'].forEach(returnedTimes => { - describe(`${returnedTimes}`, () => { - test('throw matcher error if received is spy', () => { - const spy = createSpy(jest.fn()); +describe('toHaveReturnedTimes', () => { + test('throw matcher error if received is spy', () => { + const spy = createSpy(jest.fn()); + + expect(() => + jestExpect(spy).not.toHaveReturnedTimes(2), + ).toThrowErrorMatchingSnapshot(); + }); + + test('only accepts a number argument', () => { + const fn = jest.fn(() => 42); + fn(); + jestExpect(fn).toHaveReturnedTimes(1); + [{}, [], true, 'a', new Map(), () => {}].forEach(value => { expect(() => - jestExpect(spy).not[returnedTimes](2), + jestExpect(fn).toHaveReturnedTimes(value), ).toThrowErrorMatchingSnapshot(); }); + }); - test('only accepts a number argument', () => { - const fn = jest.fn(() => 42); - fn(); - jestExpect(fn)[returnedTimes](1); + test('.not only accepts a number argument', () => { + const fn = jest.fn(() => 42); + jestExpect(fn).not.toHaveReturnedTimes(2); - [{}, [], true, 'a', new Map(), () => {}].forEach(value => { - expect(() => - jestExpect(fn)[returnedTimes](value), - ).toThrowErrorMatchingSnapshot(); - }); + [{}, [], true, 'a', new Map(), () => {}].forEach(value => { + expect(() => + jestExpect(fn).not.toHaveReturnedTimes(value), + ).toThrowErrorMatchingSnapshot(); }); + }); - test('.not only accepts a number argument', () => { - const fn = jest.fn(() => 42); - jestExpect(fn).not[returnedTimes](2); + test('passes if function returned equal to expected times', () => { + const fn = jest.fn(() => 42); + fn(); + fn(); - [{}, [], true, 'a', new Map(), () => {}].forEach(value => { - expect(() => - jestExpect(fn).not[returnedTimes](value), - ).toThrowErrorMatchingSnapshot(); - }); - }); + jestExpect(fn).toHaveReturnedTimes(2); - test('passes if function returned equal to expected times', () => { - const fn = jest.fn(() => 42); - fn(); - fn(); + expect(() => + jestExpect(fn).not.toHaveReturnedTimes(2), + ).toThrowErrorMatchingSnapshot(); + }); - jestExpect(fn)[returnedTimes](2); + test('calls that return undefined are counted as returns', () => { + const fn = jest.fn(() => undefined); + fn(); + fn(); - expect(() => - jestExpect(fn).not[returnedTimes](2), - ).toThrowErrorMatchingSnapshot(); - }); + jestExpect(fn).toHaveReturnedTimes(2); - test('calls that return undefined are counted as returns', () => { - const fn = jest.fn(() => undefined); - fn(); - fn(); + expect(() => + jestExpect(fn).not.toHaveReturnedTimes(2), + ).toThrowErrorMatchingSnapshot(); + }); - jestExpect(fn)[returnedTimes](2); + test('.not passes if function returned more than expected times', () => { + const fn = jest.fn(() => 42); + fn(); + fn(); + fn(); - expect(() => - jestExpect(fn).not[returnedTimes](2), - ).toThrowErrorMatchingSnapshot(); - }); + jestExpect(fn).toHaveReturnedTimes(3); + jestExpect(fn).not.toHaveReturnedTimes(2); - test('.not passes if function returned more than expected times', () => { - const fn = jest.fn(() => 42); - fn(); - fn(); - fn(); + expect(() => + jestExpect(fn).toHaveReturnedTimes(2), + ).toThrowErrorMatchingSnapshot(); + }); - jestExpect(fn)[returnedTimes](3); - jestExpect(fn).not[returnedTimes](2); + test('.not passes if function called less than expected times', () => { + const fn = jest.fn(() => 42); + fn(); - expect(() => - jestExpect(fn)[returnedTimes](2), - ).toThrowErrorMatchingSnapshot(); - }); + jestExpect(fn).toHaveReturnedTimes(1); + jestExpect(fn).not.toHaveReturnedTimes(2); - test('.not passes if function called less than expected times', () => { - const fn = jest.fn(() => 42); - fn(); + expect(() => + jestExpect(fn).toHaveReturnedTimes(2), + ).toThrowErrorMatchingSnapshot(); + }); - jestExpect(fn)[returnedTimes](1); - jestExpect(fn).not[returnedTimes](2); + test('calls that throw are not counted', () => { + const fn = jest.fn(causeError => { + if (causeError) { + throw new Error('Error!'); + } - expect(() => - jestExpect(fn)[returnedTimes](2), - ).toThrowErrorMatchingSnapshot(); + return 42; }); - test('calls that throw are not counted', () => { - const fn = jest.fn(causeError => { - if (causeError) { - throw new Error('Error!'); - } + fn(false); - return 42; - }); + try { + fn(true); + } catch { + // ignore error + } - fn(false); + fn(false); - try { - fn(true); - } catch { - // ignore error - } + jestExpect(fn).not.toHaveReturnedTimes(3); - fn(false); + expect(() => + jestExpect(fn).toHaveReturnedTimes(3), + ).toThrowErrorMatchingSnapshot(); + }); - jestExpect(fn).not[returnedTimes](3); + test('calls that throw undefined are not counted', () => { + const fn = jest.fn(causeError => { + if (causeError) { + // eslint-disable-next-line no-throw-literal + throw undefined; + } - expect(() => - jestExpect(fn)[returnedTimes](3), - ).toThrowErrorMatchingSnapshot(); + return 42; }); - test('calls that throw undefined are not counted', () => { - const fn = jest.fn(causeError => { - if (causeError) { - // eslint-disable-next-line no-throw-literal - throw undefined; - } - - return 42; - }); - - fn(false); + fn(false); - try { - fn(true); - } catch { - // ignore error - } + try { + fn(true); + } catch { + // ignore error + } - fn(false); + fn(false); - jestExpect(fn)[returnedTimes](2); + jestExpect(fn).toHaveReturnedTimes(2); - expect(() => - jestExpect(fn).not[returnedTimes](2), - ).toThrowErrorMatchingSnapshot(); - }); + expect(() => + jestExpect(fn).not.toHaveReturnedTimes(2), + ).toThrowErrorMatchingSnapshot(); + }); - test('includes the custom mock name in the error message', () => { - const fn = jest.fn(() => 42).mockName('named-mock'); - fn(); - fn(); + test('includes the custom mock name in the error message', () => { + const fn = jest.fn(() => 42).mockName('named-mock'); + fn(); + fn(); - jestExpect(fn)[returnedTimes](2); + jestExpect(fn).toHaveReturnedTimes(2); - expect(() => - jestExpect(fn)[returnedTimes](1), - ).toThrowErrorMatchingSnapshot(); - }); + expect(() => + jestExpect(fn).toHaveReturnedTimes(1), + ).toThrowErrorMatchingSnapshot(); + }); - test('incomplete recursive calls are handled properly', () => { - // sums up all integers from 0 -> value, using recursion - const fn: jest.Mock = jest.fn(value => { - if (value === 0) { - return 0; - } else { - const recursiveResult = fn(value - 1); - - if (value === 2) { - // Only 2 of the recursive calls have returned at this point - jestExpect(fn)[returnedTimes](2); - expect(() => - jestExpect(fn).not[returnedTimes](2), - ).toThrowErrorMatchingSnapshot(); - } - - return value + recursiveResult; + test('incomplete recursive calls are handled properly', () => { + // sums up all integers from 0 -> value, using recursion + const fn: jest.Mock = jest.fn(value => { + if (value === 0) { + return 0; + } else { + const recursiveResult = fn(value - 1); + + if (value === 2) { + // Only 2 of the recursive calls have returned at this point + jestExpect(fn).toHaveReturnedTimes(2); + expect(() => + jestExpect(fn).not.toHaveReturnedTimes(2), + ).toThrowErrorMatchingSnapshot(); } - }); - fn(3); + return value + recursiveResult; + } }); + + fn(3); }); }); diff --git a/packages/expect/src/spyMatchers.ts b/packages/expect/src/spyMatchers.ts index 24f10991df56..c7cff473148f 100644 --- a/packages/expect/src/spyMatchers.ts +++ b/packages/expect/src/spyMatchers.ts @@ -1152,7 +1152,6 @@ const spyMatchers: MatchersObject = { toHaveReturned: createToReturnMatcher('toHaveReturned'), toHaveReturnedTimes: createToReturnTimesMatcher('toHaveReturnedTimes'), toHaveReturnedWith: createToReturnWithMatcher('toHaveReturnedWith'), - toReturnTimes: createToReturnTimesMatcher('toReturnTimes'), toReturnWith: createToReturnWithMatcher('toReturnWith'), }; diff --git a/packages/expect/src/types.ts b/packages/expect/src/types.ts index 7285143d8598..02f903e38390 100644 --- a/packages/expect/src/types.ts +++ b/packages/expect/src/types.ts @@ -294,10 +294,6 @@ export interface Matchers> { toMatchObject( expected: Record | Array>, ): R; - /** - * Ensure that a mock function has returned (as opposed to thrown) a specified number of times. - */ - toReturnTimes(expected: number): R; /** * Ensure that a mock function has returned a specified value at least once. */ diff --git a/packages/jest-types/__typetests__/expect.test.ts b/packages/jest-types/__typetests__/expect.test.ts index 2c5973300631..dc65608ed883 100644 --- a/packages/jest-types/__typetests__/expect.test.ts +++ b/packages/jest-types/__typetests__/expect.test.ts @@ -221,12 +221,10 @@ expectType(expect(jest.fn()).toHaveReturned()); expectError(expect(jest.fn()).toHaveReturned('value')); expectError(expect(jest.fn()).toHaveReturned(false)); -expectType(expect(jest.fn()).toReturnTimes(1)); -expectError(expect(jest.fn()).toReturnTimes('twice')); -expectError(expect(jest.fn()).toReturnTimes()); +expectError(expect(jest.fn()).toHaveReturnedTimes()); expectType(expect(jest.fn()).toHaveReturnedTimes(3)); +expectError(expect(jest.fn()).toHaveReturnedTimes('twice')); expectError(expect(jest.fn()).toHaveReturnedTimes(true)); -expectError(expect(jest.fn()).toHaveReturnedTimes()); expectType(expect(jest.fn()).toReturnWith('value')); expectError(expect(jest.fn()).toReturnWith()); From da3ef6ce1ed4053c4a57c65b510f0f460a7061f8 Mon Sep 17 00:00:00 2001 From: EduardoSCosta Date: Mon, 29 Aug 2022 18:35:51 -0300 Subject: [PATCH 09/13] chore: remove .toReturnWith() matcher --- .../__snapshots__/spyMatchers.test.ts.snap | 145 ------------------ .../expect/src/__tests__/spyMatchers.test.ts | 4 +- packages/expect/src/spyMatchers.ts | 1 - packages/expect/src/types.ts | 4 - .../jest-types/__typetests__/expect.test.ts | 5 +- 5 files changed, 3 insertions(+), 156 deletions(-) diff --git a/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap b/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap index c3650820fe94..d127286012d4 100644 --- a/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap +++ b/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap @@ -2033,148 +2033,3 @@ Expected: not undefined Number of returns: 1 `; - -exports[`toReturnWith a call that throws is not considered to have returned 1`] = ` -expect(jest.fn()).toReturnWith(expected) - -Expected: undefined -Received: function call threw an error - -Number of returns: 0 -Number of calls: 1 -`; - -exports[`toReturnWith a call that throws undefined is not considered to have returned 1`] = ` -expect(jest.fn()).toReturnWith(expected) - -Expected: undefined -Received: function call threw an error - -Number of returns: 0 -Number of calls: 1 -`; - -exports[`toReturnWith includes the custom mock name in the error message 1`] = ` -expect(named-mock).toReturnWith(expected) - -Expected: "foo" - -Number of returns: 0 -`; - -exports[`toReturnWith returnedWith incomplete recursive calls are handled properly 1`] = ` -expect(jest.fn()).toReturnWith(expected) - -Expected: undefined -Received - 1: function call has not returned yet - 2: function call has not returned yet - 3: function call has not returned yet - -Number of returns: 0 -Number of calls: 4 -`; - -exports[`toReturnWith returnedWith works with more calls than the limit 1`] = ` -expect(jest.fn()).toReturnWith(expected) - -Expected: "bar" -Received - 1: "foo1" - 2: "foo2" - 3: "foo3" - -Number of returns: 6 -`; - -exports[`toReturnWith works only on spies or jest.fn 1`] = ` -expect(received).toReturnWith(expected) - -Matcher error: received value must be a mock function - -Received has type: function -Received has value: [Function fn] -`; - -exports[`toReturnWith works when not called 1`] = ` -expect(jest.fn()).toReturnWith(expected) - -Expected: "foo" - -Number of returns: 0 -`; - -exports[`toReturnWith works with Immutable.js objects directly created 1`] = ` -expect(jest.fn()).not.toReturnWith(expected) - -Expected: not Immutable.Map {"a": {"b": "c"}} - -Number of returns: 1 -`; - -exports[`toReturnWith works with Immutable.js objects indirectly created 1`] = ` -expect(jest.fn()).not.toReturnWith(expected) - -Expected: not Immutable.Map {"a": {"b": "c"}} - -Number of returns: 1 -`; - -exports[`toReturnWith works with Map 1`] = ` -expect(jest.fn()).not.toReturnWith(expected) - -Expected: not Map {1 => 2, 2 => 1} - -Number of returns: 1 -`; - -exports[`toReturnWith works with Map 2`] = ` -expect(jest.fn()).toReturnWith(expected) - -Expected: Map {"a" => "b", "b" => "a"} -Received: Map {1 => 2, 2 => 1} - -Number of returns: 1 -`; - -exports[`toReturnWith works with Set 1`] = ` -expect(jest.fn()).not.toReturnWith(expected) - -Expected: not Set {1, 2} - -Number of returns: 1 -`; - -exports[`toReturnWith works with Set 2`] = ` -expect(jest.fn()).toReturnWith(expected) - -Expected: Set {3, 4} -Received: Set {1, 2} - -Number of returns: 1 -`; - -exports[`toReturnWith works with argument that does match 1`] = ` -expect(jest.fn()).not.toReturnWith(expected) - -Expected: not "foo" - -Number of returns: 1 -`; - -exports[`toReturnWith works with argument that does not match 1`] = ` -expect(jest.fn()).toReturnWith(expected) - -Expected: "bar" -Received: "foo" - -Number of returns: 1 -`; - -exports[`toReturnWith works with undefined 1`] = ` -expect(jest.fn()).not.toReturnWith(expected) - -Expected: not undefined - -Number of returns: 1 -`; diff --git a/packages/expect/src/__tests__/spyMatchers.test.ts b/packages/expect/src/__tests__/spyMatchers.test.ts index e914ee121f2f..7374aa0b0b32 100644 --- a/packages/expect/src/__tests__/spyMatchers.test.ts +++ b/packages/expect/src/__tests__/spyMatchers.test.ts @@ -851,7 +851,6 @@ describe('toHaveReturnedTimes', () => { 'toHaveLastReturnedWith', 'nthReturnedWith', 'toHaveNthReturnedWith', - 'toReturnWith', 'toHaveReturnedWith', ].forEach(returnedWith => { const caller = function ( @@ -1039,8 +1038,7 @@ describe('toHaveReturnedTimes', () => { ).toThrowErrorMatchingSnapshot(); }); - const basicReturnedWith = ['toHaveReturnedWith', 'toReturnWith']; - if (basicReturnedWith.indexOf(returnedWith) >= 0) { + if (returnedWith === 'toHaveReturnedWith') { describe('returnedWith', () => { test('works with more calls than the limit', () => { const fn = jest.fn(); diff --git a/packages/expect/src/spyMatchers.ts b/packages/expect/src/spyMatchers.ts index c7cff473148f..93af7ebd10ef 100644 --- a/packages/expect/src/spyMatchers.ts +++ b/packages/expect/src/spyMatchers.ts @@ -1152,7 +1152,6 @@ const spyMatchers: MatchersObject = { toHaveReturned: createToReturnMatcher('toHaveReturned'), toHaveReturnedTimes: createToReturnTimesMatcher('toHaveReturnedTimes'), toHaveReturnedWith: createToReturnWithMatcher('toHaveReturnedWith'), - toReturnWith: createToReturnWithMatcher('toReturnWith'), }; const isMock = (received: any) => diff --git a/packages/expect/src/types.ts b/packages/expect/src/types.ts index 02f903e38390..b121f5c8e69a 100644 --- a/packages/expect/src/types.ts +++ b/packages/expect/src/types.ts @@ -294,10 +294,6 @@ export interface Matchers> { toMatchObject( expected: Record | Array>, ): R; - /** - * Ensure that a mock function has returned a specified value at least once. - */ - toReturnWith(expected: unknown): R; /** * Use to test that objects have the same types as well as structure. */ diff --git a/packages/jest-types/__typetests__/expect.test.ts b/packages/jest-types/__typetests__/expect.test.ts index dc65608ed883..634d8ab08e00 100644 --- a/packages/jest-types/__typetests__/expect.test.ts +++ b/packages/jest-types/__typetests__/expect.test.ts @@ -226,10 +226,9 @@ expectType(expect(jest.fn()).toHaveReturnedTimes(3)); expectError(expect(jest.fn()).toHaveReturnedTimes('twice')); expectError(expect(jest.fn()).toHaveReturnedTimes(true)); -expectType(expect(jest.fn()).toReturnWith('value')); -expectError(expect(jest.fn()).toReturnWith()); -expectType(expect(jest.fn()).toHaveReturnedWith(123)); expectError(expect(jest.fn()).toHaveReturnedWith()); +expectType(expect(jest.fn()).toHaveReturnedWith('value')); +expectType(expect(jest.fn()).toHaveReturnedWith(123)); expectType(expect(jest.fn()).lastReturnedWith('value')); expectError(expect(jest.fn()).lastReturnedWith()); From d873fe92742322ff29e22ef53413120040559d0e Mon Sep 17 00:00:00 2001 From: EduardoSCosta Date: Mon, 29 Aug 2022 18:54:38 -0300 Subject: [PATCH 10/13] chore: remove .lastReturnedWith() matcher --- .../__snapshots__/spyMatchers.test.ts.snap | 147 +----------------- .../expect/src/__tests__/spyMatchers.test.ts | 6 +- packages/expect/src/spyMatchers.ts | 1 - packages/expect/src/types.ts | 4 - .../jest-types/__typetests__/expect.test.ts | 5 +- 5 files changed, 6 insertions(+), 157 deletions(-) diff --git a/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap b/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap index d127286012d4..75e8ee83b2f5 100644 --- a/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap +++ b/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap @@ -1,148 +1,5 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`lastReturnedWith a call that throws is not considered to have returned 1`] = ` -expect(jest.fn()).lastReturnedWith(expected) - -Expected: undefined -Received: function call threw an error - -Number of returns: 0 -Number of calls: 1 -`; - -exports[`lastReturnedWith a call that throws undefined is not considered to have returned 1`] = ` -expect(jest.fn()).lastReturnedWith(expected) - -Expected: undefined -Received: function call threw an error - -Number of returns: 0 -Number of calls: 1 -`; - -exports[`lastReturnedWith includes the custom mock name in the error message 1`] = ` -expect(named-mock).lastReturnedWith(expected) - -Expected: "foo" - -Number of returns: 0 -`; - -exports[`lastReturnedWith lastReturnedWith incomplete recursive calls are handled properly 1`] = ` -expect(jest.fn()).lastReturnedWith(expected) - -Expected: 0 -Received - 3: function call has not returned yet --> 4: function call has not returned yet - -Number of returns: 0 -Number of calls: 4 -`; - -exports[`lastReturnedWith lastReturnedWith works with three calls 1`] = ` -expect(jest.fn()).not.lastReturnedWith(expected) - -Expected: not "foo3" -Received - 2: "foo2" --> 3: "foo3" - -Number of returns: 3 -`; - -exports[`lastReturnedWith works only on spies or jest.fn 1`] = ` -expect(received).lastReturnedWith(expected) - -Matcher error: received value must be a mock function - -Received has type: function -Received has value: [Function fn] -`; - -exports[`lastReturnedWith works when not called 1`] = ` -expect(jest.fn()).lastReturnedWith(expected) - -Expected: "foo" - -Number of returns: 0 -`; - -exports[`lastReturnedWith works with Immutable.js objects directly created 1`] = ` -expect(jest.fn()).not.lastReturnedWith(expected) - -Expected: not Immutable.Map {"a": {"b": "c"}} - -Number of returns: 1 -`; - -exports[`lastReturnedWith works with Immutable.js objects indirectly created 1`] = ` -expect(jest.fn()).not.lastReturnedWith(expected) - -Expected: not Immutable.Map {"a": {"b": "c"}} - -Number of returns: 1 -`; - -exports[`lastReturnedWith works with Map 1`] = ` -expect(jest.fn()).not.lastReturnedWith(expected) - -Expected: not Map {1 => 2, 2 => 1} - -Number of returns: 1 -`; - -exports[`lastReturnedWith works with Map 2`] = ` -expect(jest.fn()).lastReturnedWith(expected) - -Expected: Map {"a" => "b", "b" => "a"} -Received: Map {1 => 2, 2 => 1} - -Number of returns: 1 -`; - -exports[`lastReturnedWith works with Set 1`] = ` -expect(jest.fn()).not.lastReturnedWith(expected) - -Expected: not Set {1, 2} - -Number of returns: 1 -`; - -exports[`lastReturnedWith works with Set 2`] = ` -expect(jest.fn()).lastReturnedWith(expected) - -Expected: Set {3, 4} -Received: Set {1, 2} - -Number of returns: 1 -`; - -exports[`lastReturnedWith works with argument that does match 1`] = ` -expect(jest.fn()).not.lastReturnedWith(expected) - -Expected: not "foo" - -Number of returns: 1 -`; - -exports[`lastReturnedWith works with argument that does not match 1`] = ` -expect(jest.fn()).lastReturnedWith(expected) - -Expected: "bar" -Received: "foo" - -Number of returns: 1 -`; - -exports[`lastReturnedWith works with undefined 1`] = ` -expect(jest.fn()).not.lastReturnedWith(expected) - -Expected: not undefined - -Number of returns: 1 -`; - exports[`nthReturnedWith a call that throws is not considered to have returned 1`] = ` expect(jest.fn()).nthReturnedWith(n, expected) @@ -1234,7 +1091,7 @@ Expected: "foo" Number of returns: 0 `; -exports[`toHaveLastReturnedWith lastReturnedWith incomplete recursive calls are handled properly 1`] = ` +exports[`toHaveLastReturnedWith toHaveLastReturnedWith incomplete recursive calls are handled properly 1`] = ` expect(jest.fn()).toHaveLastReturnedWith(expected) Expected: 0 @@ -1246,7 +1103,7 @@ Number of returns: 0 Number of calls: 4 `; -exports[`toHaveLastReturnedWith lastReturnedWith works with three calls 1`] = ` +exports[`toHaveLastReturnedWith toHaveLastReturnedWith works with three calls 1`] = ` expect(jest.fn()).not.toHaveLastReturnedWith(expected) Expected: not "foo3" diff --git a/packages/expect/src/__tests__/spyMatchers.test.ts b/packages/expect/src/__tests__/spyMatchers.test.ts index 7374aa0b0b32..5b7d30d55c1f 100644 --- a/packages/expect/src/__tests__/spyMatchers.test.ts +++ b/packages/expect/src/__tests__/spyMatchers.test.ts @@ -847,7 +847,6 @@ describe('toHaveReturnedTimes', () => { }); [ - 'lastReturnedWith', 'toHaveLastReturnedWith', 'nthReturnedWith', 'toHaveNthReturnedWith', @@ -1208,9 +1207,8 @@ describe('toHaveReturnedTimes', () => { }); } - const lastReturnedWith = ['toHaveLastReturnedWith', 'lastReturnedWith']; - if (lastReturnedWith.indexOf(returnedWith) >= 0) { - describe('lastReturnedWith', () => { + if (returnedWith === 'toHaveLastReturnedWith') { + describe('toHaveLastReturnedWith', () => { test('works with three calls', () => { const fn = jest.fn(); fn.mockReturnValueOnce('foo1'); diff --git a/packages/expect/src/spyMatchers.ts b/packages/expect/src/spyMatchers.ts index 93af7ebd10ef..6863a6c21352 100644 --- a/packages/expect/src/spyMatchers.ts +++ b/packages/expect/src/spyMatchers.ts @@ -1136,7 +1136,6 @@ const createNthReturnedWithMatcher = (matcherName: string) => }; const spyMatchers: MatchersObject = { - lastReturnedWith: createLastReturnedMatcher('lastReturnedWith'), nthReturnedWith: createNthReturnedWithMatcher('nthReturnedWith'), toHaveBeenCalled: createToBeCalledMatcher('toHaveBeenCalled'), toHaveBeenCalledTimes: createToBeCalledTimesMatcher('toHaveBeenCalledTimes'), diff --git a/packages/expect/src/types.ts b/packages/expect/src/types.ts index b121f5c8e69a..9e2d7601495e 100644 --- a/packages/expect/src/types.ts +++ b/packages/expect/src/types.ts @@ -132,10 +132,6 @@ type PromiseMatchers = { }; export interface Matchers> { - /** - * Ensure that the last call to a mock function has returned a specified value. - */ - lastReturnedWith(expected: unknown): R; /** * Ensure that the nth call to a mock function has returned a specified value. */ diff --git a/packages/jest-types/__typetests__/expect.test.ts b/packages/jest-types/__typetests__/expect.test.ts index 634d8ab08e00..269691d3ab44 100644 --- a/packages/jest-types/__typetests__/expect.test.ts +++ b/packages/jest-types/__typetests__/expect.test.ts @@ -230,10 +230,9 @@ expectError(expect(jest.fn()).toHaveReturnedWith()); expectType(expect(jest.fn()).toHaveReturnedWith('value')); expectType(expect(jest.fn()).toHaveReturnedWith(123)); -expectType(expect(jest.fn()).lastReturnedWith('value')); -expectError(expect(jest.fn()).lastReturnedWith()); -expectType(expect(jest.fn()).toHaveLastReturnedWith(123)); expectError(expect(jest.fn()).toHaveLastReturnedWith()); +expectType(expect(jest.fn()).toHaveLastReturnedWith('value')); +expectType(expect(jest.fn()).toHaveLastReturnedWith(123)); expectType(expect(jest.fn()).nthReturnedWith(1, 'value')); expectError(expect(jest.fn()).nthReturnedWith()); From 1c4ceedd0b2dd0beed557de5b56de882649c8fb7 Mon Sep 17 00:00:00 2001 From: EduardoSCosta Date: Mon, 29 Aug 2022 19:03:34 -0300 Subject: [PATCH 11/13] chore: remove .nthReturnedWith() matcher --- .../__snapshots__/spyMatchers.test.ts.snap | 282 +----------------- .../expect/src/__tests__/spyMatchers.test.ts | 11 +- packages/expect/src/spyMatchers.ts | 1 - packages/expect/src/types.ts | 4 - .../jest-types/__typetests__/expect.test.ts | 5 +- 5 files changed, 15 insertions(+), 288 deletions(-) diff --git a/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap b/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap index 75e8ee83b2f5..a7ab745e750c 100644 --- a/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap +++ b/packages/expect/src/__tests__/__snapshots__/spyMatchers.test.ts.snap @@ -1,265 +1,5 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`nthReturnedWith a call that throws is not considered to have returned 1`] = ` -expect(jest.fn()).nthReturnedWith(n, expected) - -n: 1 -Expected: undefined -Received: function call threw an error - -Number of returns: 0 -Number of calls: 1 -`; - -exports[`nthReturnedWith a call that throws undefined is not considered to have returned 1`] = ` -expect(jest.fn()).nthReturnedWith(n, expected) - -n: 1 -Expected: undefined -Received: function call threw an error - -Number of returns: 0 -Number of calls: 1 -`; - -exports[`nthReturnedWith includes the custom mock name in the error message 1`] = ` -expect(named-mock).nthReturnedWith(n, expected) - -n: 1 -Expected: "foo" - -Number of returns: 0 -`; - -exports[`nthReturnedWith nthReturnedWith incomplete recursive calls are handled properly 1`] = ` -expect(jest.fn()).nthReturnedWith(n, expected) - -n: 1 -Expected: 6 -Received --> 1: function call has not returned yet - 2: function call has not returned yet - -Number of returns: 2 -Number of calls: 4 -`; - -exports[`nthReturnedWith nthReturnedWith incomplete recursive calls are handled properly 2`] = ` -expect(jest.fn()).nthReturnedWith(n, expected) - -n: 2 -Expected: 3 -Received - 1: function call has not returned yet --> 2: function call has not returned yet - 3: 1 - -Number of returns: 2 -Number of calls: 4 -`; - -exports[`nthReturnedWith nthReturnedWith incomplete recursive calls are handled properly 3`] = ` -expect(jest.fn()).not.nthReturnedWith(n, expected) - -n: 3 -Expected: not 1 -Received - 2: function call has not returned yet --> 3: 1 - 4: 0 - -Number of returns: 2 -Number of calls: 4 -`; - -exports[`nthReturnedWith nthReturnedWith incomplete recursive calls are handled properly 4`] = ` -expect(jest.fn()).not.nthReturnedWith(n, expected) - -n: 4 -Expected: not 0 -Received - 3: 1 --> 4: 0 - -Number of returns: 2 -Number of calls: 4 -`; - -exports[`nthReturnedWith nthReturnedWith negative throw matcher error for n that is not number 1`] = ` -expect(received).not.nthReturnedWith(n, expected) - -Matcher error: n must be a positive integer - -n has value: undefined -`; - -exports[`nthReturnedWith nthReturnedWith positive throw matcher error for n that is not integer 1`] = ` -expect(received).nthReturnedWith(n, expected) - -Matcher error: n must be a positive integer - -n has type: number -n has value: 0.1 -`; - -exports[`nthReturnedWith nthReturnedWith positive throw matcher error for n that is not positive integer 1`] = ` -expect(received).nthReturnedWith(n, expected) - -Matcher error: n must be a positive integer - -n has type: number -n has value: 0 -`; - -exports[`nthReturnedWith nthReturnedWith should reject nth value greater than number of calls 1`] = ` -expect(jest.fn()).nthReturnedWith(n, expected) - -n: 4 -Expected: "foo" -Received - 3: "foo" - -Number of returns: 3 -`; - -exports[`nthReturnedWith nthReturnedWith should replace 1st, 2nd, 3rd with first, second, third 1`] = ` -expect(jest.fn()).nthReturnedWith(n, expected) - -n: 1 -Expected: "bar1" -Received --> 1: "foo1" - 2: "foo2" - -Number of returns: 3 -`; - -exports[`nthReturnedWith nthReturnedWith should replace 1st, 2nd, 3rd with first, second, third 2`] = ` -expect(jest.fn()).not.nthReturnedWith(n, expected) - -n: 1 -Expected: not "foo1" -Received --> 1: "foo1" - 2: "foo2" - -Number of returns: 3 -`; - -exports[`nthReturnedWith nthReturnedWith works with three calls 1`] = ` -expect(jest.fn()).not.nthReturnedWith(n, expected) - -n: 1 -Expected: not "foo1" -Received --> 1: "foo1" - 2: "foo2" - -Number of returns: 3 -`; - -exports[`nthReturnedWith works only on spies or jest.fn 1`] = ` -expect(received).nthReturnedWith(n, expected) - -Matcher error: received value must be a mock function - -Received has type: function -Received has value: [Function fn] -`; - -exports[`nthReturnedWith works when not called 1`] = ` -expect(jest.fn()).nthReturnedWith(n, expected) - -n: 1 -Expected: "foo" - -Number of returns: 0 -`; - -exports[`nthReturnedWith works with Immutable.js objects directly created 1`] = ` -expect(jest.fn()).not.nthReturnedWith(n, expected) - -n: 1 -Expected: not Immutable.Map {"a": {"b": "c"}} - -Number of returns: 1 -`; - -exports[`nthReturnedWith works with Immutable.js objects indirectly created 1`] = ` -expect(jest.fn()).not.nthReturnedWith(n, expected) - -n: 1 -Expected: not Immutable.Map {"a": {"b": "c"}} - -Number of returns: 1 -`; - -exports[`nthReturnedWith works with Map 1`] = ` -expect(jest.fn()).not.nthReturnedWith(n, expected) - -n: 1 -Expected: not Map {1 => 2, 2 => 1} - -Number of returns: 1 -`; - -exports[`nthReturnedWith works with Map 2`] = ` -expect(jest.fn()).nthReturnedWith(n, expected) - -n: 1 -Expected: Map {"a" => "b", "b" => "a"} -Received: Map {1 => 2, 2 => 1} - -Number of returns: 1 -`; - -exports[`nthReturnedWith works with Set 1`] = ` -expect(jest.fn()).not.nthReturnedWith(n, expected) - -n: 1 -Expected: not Set {1, 2} - -Number of returns: 1 -`; - -exports[`nthReturnedWith works with Set 2`] = ` -expect(jest.fn()).nthReturnedWith(n, expected) - -n: 1 -Expected: Set {3, 4} -Received: Set {1, 2} - -Number of returns: 1 -`; - -exports[`nthReturnedWith works with argument that does match 1`] = ` -expect(jest.fn()).not.nthReturnedWith(n, expected) - -n: 1 -Expected: not "foo" - -Number of returns: 1 -`; - -exports[`nthReturnedWith works with argument that does not match 1`] = ` -expect(jest.fn()).nthReturnedWith(n, expected) - -n: 1 -Expected: "bar" -Received: "foo" - -Number of returns: 1 -`; - -exports[`nthReturnedWith works with undefined 1`] = ` -expect(jest.fn()).not.nthReturnedWith(n, expected) - -n: 1 -Expected: not undefined - -Number of returns: 1 -`; - exports[`toHaveBeenCalled .not fails with any argument passed 1`] = ` expect(received).not.toHaveBeenCalled() @@ -1237,7 +977,7 @@ Expected: "foo" Number of returns: 0 `; -exports[`toHaveNthReturnedWith nthReturnedWith incomplete recursive calls are handled properly 1`] = ` +exports[`toHaveNthReturnedWith toHaveNthReturnedWith incomplete recursive calls are handled properly 1`] = ` expect(jest.fn()).toHaveNthReturnedWith(n, expected) n: 1 @@ -1250,7 +990,7 @@ Number of returns: 2 Number of calls: 4 `; -exports[`toHaveNthReturnedWith nthReturnedWith incomplete recursive calls are handled properly 2`] = ` +exports[`toHaveNthReturnedWith toHaveNthReturnedWith incomplete recursive calls are handled properly 2`] = ` expect(jest.fn()).toHaveNthReturnedWith(n, expected) n: 2 @@ -1264,7 +1004,7 @@ Number of returns: 2 Number of calls: 4 `; -exports[`toHaveNthReturnedWith nthReturnedWith incomplete recursive calls are handled properly 3`] = ` +exports[`toHaveNthReturnedWith toHaveNthReturnedWith incomplete recursive calls are handled properly 3`] = ` expect(jest.fn()).not.toHaveNthReturnedWith(n, expected) n: 3 @@ -1278,7 +1018,7 @@ Number of returns: 2 Number of calls: 4 `; -exports[`toHaveNthReturnedWith nthReturnedWith incomplete recursive calls are handled properly 4`] = ` +exports[`toHaveNthReturnedWith toHaveNthReturnedWith incomplete recursive calls are handled properly 4`] = ` expect(jest.fn()).not.toHaveNthReturnedWith(n, expected) n: 4 @@ -1291,7 +1031,7 @@ Number of returns: 2 Number of calls: 4 `; -exports[`toHaveNthReturnedWith nthReturnedWith negative throw matcher error for n that is not number 1`] = ` +exports[`toHaveNthReturnedWith toHaveNthReturnedWith negative throw matcher error for n that is not number 1`] = ` expect(received).not.toHaveNthReturnedWith(n, expected) Matcher error: n must be a positive integer @@ -1299,7 +1039,7 @@ exports[`toHaveNthReturnedWith nthReturnedWith negative throw matcher error for n has value: undefined `; -exports[`toHaveNthReturnedWith nthReturnedWith positive throw matcher error for n that is not integer 1`] = ` +exports[`toHaveNthReturnedWith toHaveNthReturnedWith positive throw matcher error for n that is not integer 1`] = ` expect(received).toHaveNthReturnedWith(n, expected) Matcher error: n must be a positive integer @@ -1308,7 +1048,7 @@ n has type: number n has value: 0.1 `; -exports[`toHaveNthReturnedWith nthReturnedWith positive throw matcher error for n that is not positive integer 1`] = ` +exports[`toHaveNthReturnedWith toHaveNthReturnedWith positive throw matcher error for n that is not positive integer 1`] = ` expect(received).toHaveNthReturnedWith(n, expected) Matcher error: n must be a positive integer @@ -1317,7 +1057,7 @@ n has type: number n has value: 0 `; -exports[`toHaveNthReturnedWith nthReturnedWith should reject nth value greater than number of calls 1`] = ` +exports[`toHaveNthReturnedWith toHaveNthReturnedWith should reject nth value greater than number of calls 1`] = ` expect(jest.fn()).toHaveNthReturnedWith(n, expected) n: 4 @@ -1328,7 +1068,7 @@ Received Number of returns: 3 `; -exports[`toHaveNthReturnedWith nthReturnedWith should replace 1st, 2nd, 3rd with first, second, third 1`] = ` +exports[`toHaveNthReturnedWith toHaveNthReturnedWith should replace 1st, 2nd, 3rd with first, second, third 1`] = ` expect(jest.fn()).toHaveNthReturnedWith(n, expected) n: 1 @@ -1340,7 +1080,7 @@ Received Number of returns: 3 `; -exports[`toHaveNthReturnedWith nthReturnedWith should replace 1st, 2nd, 3rd with first, second, third 2`] = ` +exports[`toHaveNthReturnedWith toHaveNthReturnedWith should replace 1st, 2nd, 3rd with first, second, third 2`] = ` expect(jest.fn()).not.toHaveNthReturnedWith(n, expected) n: 1 @@ -1352,7 +1092,7 @@ Received Number of returns: 3 `; -exports[`toHaveNthReturnedWith nthReturnedWith works with three calls 1`] = ` +exports[`toHaveNthReturnedWith toHaveNthReturnedWith works with three calls 1`] = ` expect(jest.fn()).not.toHaveNthReturnedWith(n, expected) n: 1 diff --git a/packages/expect/src/__tests__/spyMatchers.test.ts b/packages/expect/src/__tests__/spyMatchers.test.ts index 5b7d30d55c1f..c3c783026833 100644 --- a/packages/expect/src/__tests__/spyMatchers.test.ts +++ b/packages/expect/src/__tests__/spyMatchers.test.ts @@ -848,7 +848,6 @@ describe('toHaveReturnedTimes', () => { [ 'toHaveLastReturnedWith', - 'nthReturnedWith', 'toHaveNthReturnedWith', 'toHaveReturnedWith', ].forEach(returnedWith => { @@ -856,10 +855,7 @@ describe('toHaveReturnedTimes', () => { callee: (...a: Array) => void, ...args: Array ) { - if ( - returnedWith === 'nthReturnedWith' || - returnedWith === 'toHaveNthReturnedWith' - ) { + if (returnedWith === 'toHaveNthReturnedWith') { callee(1, ...args); } else { callee(...args); @@ -1086,9 +1082,8 @@ describe('toHaveReturnedTimes', () => { }); } - const nthReturnedWith = ['toHaveNthReturnedWith', 'nthReturnedWith']; - if (nthReturnedWith.indexOf(returnedWith) >= 0) { - describe('nthReturnedWith', () => { + if (returnedWith === 'toHaveNthReturnedWith') { + describe('toHaveNthReturnedWith', () => { test('works with three calls', () => { const fn = jest.fn(); fn.mockReturnValueOnce('foo1'); diff --git a/packages/expect/src/spyMatchers.ts b/packages/expect/src/spyMatchers.ts index 6863a6c21352..f145ed5fb1fa 100644 --- a/packages/expect/src/spyMatchers.ts +++ b/packages/expect/src/spyMatchers.ts @@ -1136,7 +1136,6 @@ const createNthReturnedWithMatcher = (matcherName: string) => }; const spyMatchers: MatchersObject = { - nthReturnedWith: createNthReturnedWithMatcher('nthReturnedWith'), toHaveBeenCalled: createToBeCalledMatcher('toHaveBeenCalled'), toHaveBeenCalledTimes: createToBeCalledTimesMatcher('toHaveBeenCalledTimes'), toHaveBeenCalledWith: createToBeCalledWithMatcher('toHaveBeenCalledWith'), diff --git a/packages/expect/src/types.ts b/packages/expect/src/types.ts index 9e2d7601495e..a4698cbc367f 100644 --- a/packages/expect/src/types.ts +++ b/packages/expect/src/types.ts @@ -132,10 +132,6 @@ type PromiseMatchers = { }; export interface Matchers> { - /** - * Ensure that the nth call to a mock function has returned a specified value. - */ - nthReturnedWith(nth: number, expected: unknown): R; /** * Checks that a value is what you expect. It calls `Object.is` to compare values. * Don't use `toBe` with floating-point numbers. diff --git a/packages/jest-types/__typetests__/expect.test.ts b/packages/jest-types/__typetests__/expect.test.ts index 269691d3ab44..b91d0a9872b5 100644 --- a/packages/jest-types/__typetests__/expect.test.ts +++ b/packages/jest-types/__typetests__/expect.test.ts @@ -234,11 +234,8 @@ expectError(expect(jest.fn()).toHaveLastReturnedWith()); expectType(expect(jest.fn()).toHaveLastReturnedWith('value')); expectType(expect(jest.fn()).toHaveLastReturnedWith(123)); -expectType(expect(jest.fn()).nthReturnedWith(1, 'value')); -expectError(expect(jest.fn()).nthReturnedWith()); -expectError(expect(jest.fn()).nthReturnedWith(2)); -expectType(expect(jest.fn()).toHaveNthReturnedWith(1, 'value')); expectError(expect(jest.fn()).toHaveNthReturnedWith()); +expectType(expect(jest.fn()).toHaveNthReturnedWith(1, 'value')); expectError(expect(jest.fn()).toHaveNthReturnedWith(2)); // snapshot matchers From 336d803199bc0ad80328d0329f93a4eaf134af45 Mon Sep 17 00:00:00 2001 From: EduardoSCosta Date: Mon, 29 Aug 2022 19:20:33 -0300 Subject: [PATCH 12/13] docs: remove eliminated matchers from docs --- docs/ExpectAPI.md | 40 +++++++++------------------------------- docs/GlobalAPI.md | 4 ++-- docs/MockFunctionAPI.md | 4 ++-- docs/TimerMocks.md | 10 +++++----- docs/TutorialjQuery.md | 2 +- 5 files changed, 19 insertions(+), 41 deletions(-) diff --git a/docs/ExpectAPI.md b/docs/ExpectAPI.md index aa25136d861b..f042709e319f 100644 --- a/docs/ExpectAPI.md +++ b/docs/ExpectAPI.md @@ -352,7 +352,7 @@ it('transitions as expected', () => { test('map calls its argument with a non-null argument', () => { const mock = jest.fn(); [1].map(x => mock(x)); - expect(mock).toBeCalledWith(expect.anything()); + expect(mock).toHaveBeenCalledWith(expect.anything()); }); ``` @@ -369,7 +369,7 @@ function getCat(fn) { test('randocall calls its callback with a class instance', () => { const mock = jest.fn(); getCat(mock); - expect(mock).toBeCalledWith(expect.any(Cat)); + expect(mock).toHaveBeenCalledWith(expect.any(Cat)); }); function randocall(fn) { @@ -379,7 +379,7 @@ function randocall(fn) { test('randocall calls its callback with a number', () => { const mock = jest.fn(); randocall(mock); - expect(mock).toBeCalledWith(expect.any(Number)); + expect(mock).toHaveBeenCalledWith(expect.any(Number)); }); ``` @@ -558,7 +558,7 @@ For example, let's say that we expect an `onPress` function to be called with an test('onPress gets called with the right thing', () => { const onPress = jest.fn(); simulatePresses(onPress); - expect(onPress).toBeCalledWith( + expect(onPress).toHaveBeenCalledWith( expect.objectContaining({ x: expect.any(Number), y: expect.any(Number), @@ -713,8 +713,6 @@ Although the `.toBe` matcher **checks** referential identity, it **reports** a d ### `.toHaveBeenCalled()` -Also under the alias: `.toBeCalled()` - Use `.toHaveBeenCalledWith` to ensure that a mock function was called with specific arguments. The arguments are checked with the same algorithm that `.toEqual` uses. For example, let's say you have a `drinkAll(drink, flavour)` function that takes a `drink` function and applies it to all available beverages. You might want to check that `drink` gets called for `'lemon'`, but not for `'octopus'`, because `'octopus'` flavour is really weird and why would anything be octopus-flavoured? You can do that with this test suite: @@ -743,8 +741,6 @@ describe('drinkAll', () => { ### `.toHaveBeenCalledTimes(number)` -Also under the alias: `.toBeCalledTimes(number)` - Use `.toHaveBeenCalledTimes` to ensure that a mock function got called exact number of times. For example, let's say you have a `drinkEach(drink, Array)` function that takes a `drink` function and applies it to array of passed beverages. You might want to check that drink function was called exact number of times. You can do that with this test suite: @@ -759,8 +755,6 @@ test('drinkEach drinks each drink', () => { ### `.toHaveBeenCalledWith(arg1, arg2, ...)` -Also under the alias: `.toBeCalledWith()` - Use `.toHaveBeenCalledWith` to ensure that a mock function was called with specific arguments. The arguments are checked with the same algorithm that `.toEqual` uses. For example, let's say that you can register a beverage with a `register` function, and `applyToAll(f)` should apply the function `f` to all registered beverages. To make sure this works, you could write: @@ -777,8 +771,6 @@ test('registration applies correctly to orange La Croix', () => { ### `.toHaveBeenLastCalledWith(arg1, arg2, ...)` -Also under the alias: `.lastCalledWith(arg1, arg2, ...)` - If you have a mock function, you can use `.toHaveBeenLastCalledWith` to test what arguments it was last called with. For example, let's say you have a `applyToAllFlavors(f)` function that applies `f` to a bunch of flavors, and you want to ensure that when you call it, the last flavor it operates on is `'mango'`. You can write: ```js @@ -791,8 +783,6 @@ test('applying to all flavors does mango last', () => { ### `.toHaveBeenNthCalledWith(nthCall, arg1, arg2, ....)` -Also under the alias: `.nthCalledWith(nthCall, arg1, arg2, ...)` - If you have a mock function, you can use `.toHaveBeenNthCalledWith` to test what arguments it was nth called with. For example, let's say you have a `drinkEach(drink, Array)` function that applies `f` to a bunch of flavors, and you want to ensure that when you call it, the first flavor it operates on is `'lemon'` and the second one is `'octopus'`. You can write: ```js @@ -812,8 +802,6 @@ The nth argument must be positive integer starting from 1. ### `.toHaveReturned()` -Also under the alias: `.toReturn()` - If you have a mock function, you can use `.toHaveReturned` to test that the mock function successfully returned (i.e., did not throw an error) at least one time. For example, let's say you have a mock `drink` that returns `true`. You can write: ```js @@ -828,8 +816,6 @@ test('drinks returns', () => { ### `.toHaveReturnedTimes(number)` -Also under the alias: `.toReturnTimes(number)` - Use `.toHaveReturnedTimes` to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times. Any calls to the mock function that throw an error are not counted toward the number of times the function returned. For example, let's say you have a mock `drink` that returns `true`. You can write: @@ -847,8 +833,6 @@ test('drink returns twice', () => { ### `.toHaveReturnedWith(value)` -Also under the alias: `.toReturnWith(value)` - Use `.toHaveReturnedWith` to ensure that a mock function returned a specific value. For example, let's say you have a mock `drink` that returns the name of the beverage that was consumed. You can write: @@ -866,8 +850,6 @@ test('drink returns La Croix', () => { ### `.toHaveLastReturnedWith(value)` -Also under the alias: `.lastReturnedWith(value)` - Use `.toHaveLastReturnedWith` to test the specific value that a mock function last returned. If the last call to the mock function threw an error, then this matcher will fail no matter what value you provided as the expected return value. For example, let's say you have a mock `drink` that returns the name of the beverage that was consumed. You can write: @@ -887,8 +869,6 @@ test('drink returns La Croix (Orange) last', () => { ### `.toHaveNthReturnedWith(nthCall, value)` -Also under the alias: `.nthReturnedWith(nthCall, value)` - Use `.toHaveNthReturnedWith` to test the specific value that a mock function returned for the nth call. If the nth call to the mock function threw an error, then this matcher will fail no matter what value you provided as the expected return value. For example, let's say you have a mock `drink` that returns the name of the beverage that was consumed. You can write: @@ -1344,8 +1324,6 @@ describe('the La Croix cans on my desk', () => { ### `.toThrow(error?)` -Also under the alias: `.toThrowError(error?)` - Use `.toThrow` to test that a function throws when it is called. For example, if we want to test that `drinkFlavor('octopus')` throws, because octopus flavor is too disgusting to drink, we could write: ```js @@ -1389,15 +1367,15 @@ test('throws on octopus', () => { } // Test that the error message says "yuck" somewhere: these are equivalent - expect(drinkOctopus).toThrowError(/yuck/); - expect(drinkOctopus).toThrowError('yuck'); + expect(drinkOctopus).toThrow(/yuck/); + expect(drinkOctopus).toThrow('yuck'); // Test the exact error message - expect(drinkOctopus).toThrowError(/^yuck, octopus flavor$/); - expect(drinkOctopus).toThrowError(new Error('yuck, octopus flavor')); + expect(drinkOctopus).toThrow(/^yuck, octopus flavor$/); + expect(drinkOctopus).toThrow(new Error('yuck, octopus flavor')); // Test that we get a DisgustingFlavorError - expect(drinkOctopus).toThrowError(DisgustingFlavorError); + expect(drinkOctopus).toThrow(DisgustingFlavorError); }); ``` diff --git a/docs/GlobalAPI.md b/docs/GlobalAPI.md index 383ce6845e98..1fe6460a8298 100644 --- a/docs/GlobalAPI.md +++ b/docs/GlobalAPI.md @@ -208,11 +208,11 @@ const binaryStringToNumber = binString => { describe('binaryStringToNumber', () => { describe('given an invalid binary string', () => { test('composed of non-numbers throws CustomError', () => { - expect(() => binaryStringToNumber('abc')).toThrowError(CustomError); + expect(() => binaryStringToNumber('abc')).toThrow(CustomError); }); test('with extra whitespace throws CustomError', () => { - expect(() => binaryStringToNumber(' 100')).toThrowError(CustomError); + expect(() => binaryStringToNumber(' 100')).toThrow(CustomError); }); }); diff --git a/docs/MockFunctionAPI.md b/docs/MockFunctionAPI.md index 526110167a84..ac5b585bb49b 100644 --- a/docs/MockFunctionAPI.md +++ b/docs/MockFunctionAPI.md @@ -516,8 +516,8 @@ test('calculate calls add', () => { // requiring `add`. calculate(mockAdd, 1, 2); - expect(mockAdd).toBeCalledTimes(1); - expect(mockAdd).toBeCalledWith(1, 2); + expect(mockAdd).toHaveBeenCalledTimes(1); + expect(mockAdd).toHaveBeenCalledWith(1, 2); }); ``` diff --git a/docs/TimerMocks.md b/docs/TimerMocks.md index 1e0260c7def6..fb53640baccf 100644 --- a/docs/TimerMocks.md +++ b/docs/TimerMocks.md @@ -53,13 +53,13 @@ test('calls the callback after 1 second', () => { timerGame(callback); // At this point in time, the callback should not have been called yet - expect(callback).not.toBeCalled(); + expect(callback).not.toHaveBeenCalled(); // Fast-forward until all timers have been executed jest.runAllTimers(); // Now our callback should have been called! - expect(callback).toBeCalled(); + expect(callback).toHaveBeenCalled(); expect(callback).toHaveBeenCalledTimes(1); }); ``` @@ -109,7 +109,7 @@ describe('infiniteTimerGame', () => { jest.runOnlyPendingTimers(); // At this point, our 1-second timer should have fired its callback - expect(callback).toBeCalled(); + expect(callback).toHaveBeenCalled(); // And it should have created a new timer to start the game over in // 10 seconds @@ -154,13 +154,13 @@ it('calls the callback after 1 second via advanceTimersByTime', () => { timerGame(callback); // At this point in time, the callback should not have been called yet - expect(callback).not.toBeCalled(); + expect(callback).not.toHaveBeenCalled(); // Fast-forward until all timers have been executed jest.advanceTimersByTime(1000); // Now our callback should have been called! - expect(callback).toBeCalled(); + expect(callback).toHaveBeenCalled(); expect(callback).toHaveBeenCalledTimes(1); }); ``` diff --git a/docs/TutorialjQuery.md b/docs/TutorialjQuery.md index 99a7bb63979d..0d875800d8e1 100644 --- a/docs/TutorialjQuery.md +++ b/docs/TutorialjQuery.md @@ -54,7 +54,7 @@ test('displays a user after a click', () => { // Assert that the fetchCurrentUser function was called, and that the // #username span's inner text was updated as we'd expect it to. - expect(fetchCurrentUser).toBeCalled(); + expect(fetchCurrentUser).toHaveBeenCalled(); expect($('#username').text()).toEqual('Johnny Cash - Logged In'); }); ``` From 89b38441f8310dc1ee8397533d76b06ec7763eea Mon Sep 17 00:00:00 2001 From: EduardoSCosta Date: Tue, 30 Aug 2022 10:51:31 -0300 Subject: [PATCH 13/13] Update CHANGELOG.md --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 80867e863a56..ed1406948718 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,9 @@ ### Chore & Maintenance +- `[expect]` [**BREAKING**] Remove `.toBeCalled()`, `.toBeCalledTimes()`, `.toBeCalledWith()`, `.lastCalledWith()`, `.nthCalledWith()`, `.toReturn()`, `.toReturnTimes()`, `.toReturnWith()`, `.lastReturnedWith()`, `.nthReturnedWith()` and `.toThrowError()` matchers ([#13192](https://github.com/facebook/jest/pull/13192)) +- `[docs]` Remove `.toBeCalled()`, `.toBeCalledTimes()`, `.toBeCalledWith()`, `.lastCalledWith()`, `.nthCalledWith()`, `.toReturn()`, `.toReturnTimes()`, `.toReturnWith()`, `.lastReturnedWith()`, `.nthReturnedWith()` and `.toThrowError()` matchers from docs ([#13192](https://github.com/facebook/jest/pull/13192)) + ### Performance ## 29.0.1