Reputation: 84
in my code I have a factory method that produces an object based on injected dependencies:
const myFactory = (myRepository : Repository) => ({
myMethod() {
return myRepository.repositoryMethod();
}
})
then in my vitest test I want to mock myRepository
when testing myFactory
output:
const myRepositoryMock = <Repository><unknown>{
repositoryMethod: vi.fn(),
}
describe('MyFactory test suite', () => {
it('myMethod test', () => {
const repositoryMethod = vi.spyOn(myRepositoryMock, 'repositoryMethod')
.mockReturnValue({ foo: 'bar' })
const myService = myFactory(myRepositoryMock);
expect(myService.myMethod()).toStrictEqual({ foo: 'bar' });
expect(repositoryMethod).toHaveBeenCalledOnce();
});
});
so far, so good - it all works as expected, however what I don't like about this solution is temporary type conversion to unknown
i.e.:
const myRepositoryMock = <Repository><unknown>{/* ... */}
I use it for readability. Basically Repository
has lots of methods from which just one is relevant to this particular test and I do not want to have them all explicitly listed in my mock.
Do you know if/how can I get rid of <unknown>
type conversion w/o having to add all methods specified in Repository
type to myRepositoryMock
?
Upvotes: 0
Views: 395
Reputation: 84
it looks like an answer is:
const myRepositoryMock : Pick<Repository, "repositoryMethod"> = {/* ... */}
lmk if you come upon a better one.
Upvotes: 0