From 508f3f568f7e278d45bc06ea91c5caa25df16a7e Mon Sep 17 00:00:00 2001 From: Simon Holloway Date: Thu, 11 Jan 2024 01:14:44 +0000 Subject: [PATCH] refactor(expect): prepare for `noUncheckedIndexedAccess` (#4150) * refactor(expect): prepare for `noUncheckedIndexedAccess` * test(expect): better error messages for missing mock call * test(expect): follow testing naming guidelines * tweak --------- Co-authored-by: Asher Gomez --- expect/_matchers.ts | 8 ++++---- expect/_to_have_been_nth_called_with_test.ts | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/expect/_matchers.ts b/expect/_matchers.ts index a676b2cf7d54..172dd71eb778 100644 --- a/expect/_matchers.ts +++ b/expect/_matchers.ts @@ -542,7 +542,7 @@ export function toHaveBeenLastCalledWith( ): MatchResult { const calls = getMockCalls(context.value); const hasBeenCalled = calls.length > 0 && - equal(calls[calls.length - 1].args, expected); + equal(calls.at(-1)?.args, expected); if (context.isNot) { if (hasBeenCalled) { @@ -583,7 +583,7 @@ export function toHaveBeenNthCalledWith( const calls = getMockCalls(context.value); const callIndex = nth - 1; const hasBeenCalled = calls.length > callIndex && - equal(calls[callIndex].args, expected); + equal(calls[callIndex]?.args, expected); if (context.isNot) { if (hasBeenCalled) { @@ -596,7 +596,7 @@ export function toHaveBeenNthCalledWith( } else { if (!hasBeenCalled) { const nthCall = calls[callIndex]; - if (!nth) { + if (!nthCall) { throw new AssertionError( `Expected the n-th call (n=${nth}) of mock function is with ${ inspectArgs(expected) @@ -689,7 +689,7 @@ export function toHaveLastReturnedWith( const calls = getMockCalls(context.value); const returned = calls.filter((call) => call.returns); const lastReturnedWithExpected = returned.length > 0 && - equal(returned[returned.length - 1].returned, expected); + equal(returned.at(-1)?.returned, expected); if (context.isNot) { if (lastReturnedWithExpected) { diff --git a/expect/_to_have_been_nth_called_with_test.ts b/expect/_to_have_been_nth_called_with_test.ts index eb3899b9c03b..0d7773fcb00e 100644 --- a/expect/_to_have_been_nth_called_with_test.ts +++ b/expect/_to_have_been_nth_called_with_test.ts @@ -27,3 +27,18 @@ Deno.test("expect().", () => { expect(mockFn).not.toHaveBeenNthCalledWith(2, 4, 5, 6); }); }); + +Deno.test("expect().toHaveBeenNthCalledWith() should throw when mock call does not exist", () => { + const mockFn = fn(); + + mockFn("hello"); + + expect(mockFn).toHaveBeenNthCalledWith(1, "hello"); + assertThrows( + () => { + expect(mockFn).toHaveBeenNthCalledWith(2, "hello"); + }, + AssertionError, + 'Expected the n-th call (n=2) of mock function is with "hello", but the n-th call does not exist.', + ); +});