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

mock module failure #6456

Open
4 tasks done
hax opened this issue Sep 6, 2024 · 2 comments
Open
4 tasks done

mock module failure #6456

hax opened this issue Sep 6, 2024 · 2 comments
Labels
p2-nice-to-have Not breaking anything but nice to have (priority)

Comments

@hax
Copy link

hax commented Sep 6, 2024

Clear and concise description of the problem

Some times we write the conditional logic rely on the result of dynamic import, eg.

export function foo() {
  try {
    const { foo } = await import("foo-lib")
    return foo()
  } catch {
    // fallback
    return fooImpl()
  }
}

function fooImpl() { ... }

To test the logic, we need to mock the module failure. But vi.mock("foo-lib", () => { throw "failure" }) doesn't work. Currently, we use __mock__ file as the workaround, but it's really annoy to add the mock files which only have simple throw statement in them. And it also means we can't use __mock__ files for normal cases.

Suggested solution

Let's introduce a new API to mock module failure: vi.mockFailure(path).

Alternative

No response

Additional context

No response

Validations

@sheremet-va
Copy link
Member

sheremet-va commented Sep 7, 2024

That's an interesting issue. I am assuming you experience this issue?

'[vitest] There was an error when mocking a module. '

I don't like introducing new methods, but maybe we can add an option to ignore failures. For example:

import { vi } from 'vitest'

vi.mock("foo-lib", { throws: true }, () => { throw "failure" })

@sheremet-va sheremet-va added p2-to-be-discussed Enhancement under consideration (priority) and removed enhancement: pending triage labels Sep 7, 2024
@hax
Copy link
Author

hax commented Sep 8, 2024

I am assuming you experience this issue?

Yes.

but maybe we can add an option to ignore failures

I understand the options and factory could provide flexibility so you can mock a module only fails in some conditions. Our case don't need such flexibility so I only proposed a simple method, but yes, options may be a more general solution.

@sheremet-va sheremet-va added p2-nice-to-have Not breaking anything but nice to have (priority) and removed p2-to-be-discussed Enhancement under consideration (priority) labels Sep 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
p2-nice-to-have Not breaking anything but nice to have (priority)
Projects
Status: Approved
Development

No branches or pull requests

2 participants