Skip to content

Commit

Permalink
refactor(expect): prepare for noUncheckedIndexedAccess (#4150)
Browse files Browse the repository at this point in the history
* 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 <ashersaupingomez@gmail.com>
  • Loading branch information
syhol and iuioiua committed Jan 11, 2024
1 parent a710c21 commit 508f3f5
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
8 changes: 4 additions & 4 deletions expect/_matchers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand All @@ -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)
Expand Down Expand Up @@ -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) {
Expand Down
15 changes: 15 additions & 0 deletions expect/_to_have_been_nth_called_with_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.',
);
});

0 comments on commit 508f3f5

Please sign in to comment.