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

Infer actual types for mock properties passed to fromPartial #12

Open
acelaya opened this issue May 11, 2024 · 2 comments
Open

Infer actual types for mock properties passed to fromPartial #12

acelaya opened this issue May 11, 2024 · 2 comments

Comments

@acelaya
Copy link

acelaya commented May 11, 2024

I'm not sure if this is even possible. I have tried a couple approaches in userland code, without successful results.

Basically, I would like to be able to do something like this:

class MyService {
  public doSomething(foo: string) {}
}

class OtherService {
  constructor(myService: MyService) {}
}

// ...

const myServiceMock = fromPartial<MyService>({ doSomething: vi.fn() });
const otherServiceInstance = new OtherService(myServiceMock);

myServiceMock.doSomething.mockReturnedValue(...);

In this example, vi is globally exposed by vitest, but the expectation would be that jest.fn() and similars also work.

At the moment this is not possible, because myServiceMock is inferred strictly as MyService, instead of, let's say MyService & { doSomething: Mock<...> }.

What I'm doing at the moment to work around this is:

const doSomething = vi.fn();
const myServiceMock = fromPartial<MyService>({ doSomething });

doSomething.mockReturnValue(...);

But with this you loose a bit of context of what doSomething is, if you don't go back to the declaration and see it is being passed to the mock.

@mattpocock
Copy link
Collaborator

There is definitely something that could be done here:

fromPartial<MyService>()({ doSomething: vi.fn() });

So, adding an overload to fromPartial that, when it receives no arguments, it returns a function. Then, in that second function call, you could infer from what's passed.

It's a question of whether the polymorphism of the API (and the resulting complexity) is worth it.

@acelaya
Copy link
Author

acelaya commented May 15, 2024

To clarify, I don't mind keeping that in my code, as I understand trying to cover too many cases here would make things messy.

I initially wrote this as a feature request, but it's also an ask for help, as I have tried to do that myself and failed dramatically 😅

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

No branches or pull requests

2 participants