Skip to content

Commit

Permalink
fix(expect): fix toHaveBeenNthCalledWith error message when not cal…
Browse files Browse the repository at this point in the history
…led (#5420)
  • Loading branch information
hi-ogawa committed Mar 26, 2024
1 parent 6fb1528 commit e5253de
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 2 deletions.
7 changes: 5 additions & 2 deletions packages/expect/src/jest-expect.ts
Expand Up @@ -521,13 +521,16 @@ export const JestChaiExpect: ChaiPlugin = (chai, utils) => {
const spy = getSpy(this)
const spyName = spy.getMockName()
const nthCall = spy.mock.calls[times - 1]

const callCount = spy.mock.calls.length
const isCalled = times <= callCount
this.assert(
jestEquals(nthCall, args, [...customTesters, iterableEquality]),
`expected ${ordinalOf(times)} "${spyName}" call to have been called with #{exp}`,
`expected ${ordinalOf(times)} "${spyName}" call to have been called with #{exp}${
isCalled ? `` : `, but called only ${callCount} times`}`,
`expected ${ordinalOf(times)} "${spyName}" call to not have been called with #{exp}`,
args,
nthCall,
isCalled,
)
})
def(['toHaveBeenLastCalledWith', 'lastCalledWith'], function (...args: any[]) {
Expand Down
30 changes: 30 additions & 0 deletions test/core/test/__snapshots__/jest-expect.test.ts.snap
Expand Up @@ -311,6 +311,36 @@ exports[`asymmetric matcher error 23`] = `
}
`;
exports[`toHaveBeenNthCalledWith error 1`] = `
{
"actual": "Array [
"Hi",
]",
"diff": "- Expected
+ Received
Array [
- "hey",
+ "Hi",
]",
"expected": "Array [
"hey",
]",
"message": "expected 2nd "spy" call to have been called with [ 'hey' ]",
}
`;
exports[`toHaveBeenNthCalledWith error 2`] = `
{
"actual": "undefined",
"diff": undefined,
"expected": "Array [
"hey",
]",
"message": "expected 3rd "spy" call to have been called with [ 'hey' ], but called only 2 times",
}
`;
exports[`toMatch/toContain diff 1`] = `
{
"actual": "hellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohello",
Expand Down
8 changes: 8 additions & 0 deletions test/core/test/jest-expect.test.ts
Expand Up @@ -1085,6 +1085,14 @@ it('asymmetric matcher error', () => {
}).toThrow(MyError1))
})

it('toHaveBeenNthCalledWith error', () => {
const fn = vi.fn()
fn('World')
fn('Hi')
snapshotError(() => expect(fn).toHaveBeenNthCalledWith(2, 'hey'))
snapshotError(() => expect(fn).toHaveBeenNthCalledWith(3, 'hey'))
})

it('toMatch/toContain diff', () => {
snapshotError(() => expect('hello'.repeat(20)).toContain('world'))
snapshotError(() => expect('hello'.repeat(20)).toMatch('world'))
Expand Down

0 comments on commit e5253de

Please sign in to comment.