Skip to content

Commit e5253de

Browse files
authoredMar 26, 2024··
fix(expect): fix toHaveBeenNthCalledWith error message when not called (#5420)
1 parent 6fb1528 commit e5253de

File tree

3 files changed

+43
-2
lines changed

3 files changed

+43
-2
lines changed
 

‎packages/expect/src/jest-expect.ts

+5-2
Original file line numberDiff line numberDiff line change
@@ -521,13 +521,16 @@ export const JestChaiExpect: ChaiPlugin = (chai, utils) => {
521521
const spy = getSpy(this)
522522
const spyName = spy.getMockName()
523523
const nthCall = spy.mock.calls[times - 1]
524-
524+
const callCount = spy.mock.calls.length
525+
const isCalled = times <= callCount
525526
this.assert(
526527
jestEquals(nthCall, args, [...customTesters, iterableEquality]),
527-
`expected ${ordinalOf(times)} "${spyName}" call to have been called with #{exp}`,
528+
`expected ${ordinalOf(times)} "${spyName}" call to have been called with #{exp}${
529+
isCalled ? `` : `, but called only ${callCount} times`}`,
528530
`expected ${ordinalOf(times)} "${spyName}" call to not have been called with #{exp}`,
529531
args,
530532
nthCall,
533+
isCalled,
531534
)
532535
})
533536
def(['toHaveBeenLastCalledWith', 'lastCalledWith'], function (...args: any[]) {

‎test/core/test/__snapshots__/jest-expect.test.ts.snap

+30
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,36 @@ exports[`asymmetric matcher error 23`] = `
311311
}
312312
`;
313313
314+
exports[`toHaveBeenNthCalledWith error 1`] = `
315+
{
316+
"actual": "Array [
317+
"Hi",
318+
]",
319+
"diff": "- Expected
320+
+ Received
321+
322+
Array [
323+
- "hey",
324+
+ "Hi",
325+
]",
326+
"expected": "Array [
327+
"hey",
328+
]",
329+
"message": "expected 2nd "spy" call to have been called with [ 'hey' ]",
330+
}
331+
`;
332+
333+
exports[`toHaveBeenNthCalledWith error 2`] = `
334+
{
335+
"actual": "undefined",
336+
"diff": undefined,
337+
"expected": "Array [
338+
"hey",
339+
]",
340+
"message": "expected 3rd "spy" call to have been called with [ 'hey' ], but called only 2 times",
341+
}
342+
`;
343+
314344
exports[`toMatch/toContain diff 1`] = `
315345
{
316346
"actual": "hellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohello",

‎test/core/test/jest-expect.test.ts

+8
Original file line numberDiff line numberDiff line change
@@ -1085,6 +1085,14 @@ it('asymmetric matcher error', () => {
10851085
}).toThrow(MyError1))
10861086
})
10871087

1088+
it('toHaveBeenNthCalledWith error', () => {
1089+
const fn = vi.fn()
1090+
fn('World')
1091+
fn('Hi')
1092+
snapshotError(() => expect(fn).toHaveBeenNthCalledWith(2, 'hey'))
1093+
snapshotError(() => expect(fn).toHaveBeenNthCalledWith(3, 'hey'))
1094+
})
1095+
10881096
it('toMatch/toContain diff', () => {
10891097
snapshotError(() => expect('hello'.repeat(20)).toContain('world'))
10901098
snapshotError(() => expect('hello'.repeat(20)).toMatch('world'))

0 commit comments

Comments
 (0)
Please sign in to comment.