Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

expect.toHaveReturned does not return true when a mock function is updated to return value #2849

Closed
6 tasks done
trivikr opened this issue Feb 11, 2023 · 3 comments · Fixed by #2850
Closed
6 tasks done

Comments

@trivikr
Copy link
Contributor

trivikr commented Feb 11, 2023

Describe the bug

expect.toHaveReturned does not return true when a mock function is updated to return value

Reproduction

Code:

import { expect, test, vi } from "vitest";

test("toHaveReturned", () => {
  const mockError = new Error("mockError");
  const mockFn = vi.fn(() => { throw mockError; });

  try {
    mockFn();
  } catch (error) {}
  expect(mockFn).not.toHaveReturned();

  const mockReturn = 42;
  mockFn.mockReturnValue(mockReturn);
  const mockOutput = mockFn();
  expect(mockOutput).toBe(mockReturn);
  expect(mockFn).toHaveReturned(); // <-- This should be true.
});

Output:

AssertionError: expected "spy" to be successfully called at least once
 ❯ src/__fixtures__/expect/toHaveReturned.output.js:15:18
     13|   const mockOutput = mockFn();
     14|   expect(mockOutput).toBe(mockReturn);
     15|   expect(mockFn).toHaveReturned();
       |                  ^
     16| });

  - Expected   "false"
  + Received   "true"

System Info

System:
    OS: macOS 13.1
    CPU: (8) arm64 Apple M1 Pro
  Binaries:
    Node: 18.13.0 - ~/Library/Caches/fnm_multishells/43666_1676070339954/bin/node
    npm: 8.19.3 - ~/Library/Caches/fnm_multishells/43666_1676070339954/bin/npm
  npmPackages:
    vitest: ^0.28.4 => 0.28.4

Used Package Manager

yarn

Validations

@trivikr
Copy link
Contributor Author

trivikr commented Feb 11, 2023

I guess the following line need to check if function had called and returned

const calledAndNotThrew = spy.mock.calls.length > 0 && !spy.mock.results.some(({ type }) => type === 'throw')

const calledAndNotThrew = spy.mock.calls.length > 0 && spy.mock.results.some(({ type }) => type === "return");

@trivikr
Copy link
Contributor Author

trivikr commented Feb 11, 2023

From vitest docs:

This assertion checks if a function has successfully returned a value at least once (i.e., did not throw an error).

https://vitest.dev/api/expect.html#tohavereturned

@trivikr
Copy link
Contributor Author

trivikr commented Feb 11, 2023

Posted a fix at #2850

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant