Comments (9)
These workarounds are very verbose and hard-to-read, and somewhat defeat the purpose of using jest-mock-extended. Since most of the mocks we use are for OpenAPI generated services which make generous use of overloading, this issue negates much of the value of jest-mock-extended in our projects. Worse, there is no decent documentation about how to use this workaround with mockReturnValue, etc.
from jest-mock-extended.
I ran into the same issue when mocking Fingerprintjs2
; Fingerprint2.get.mockImplementation
expected the one argument signature, but I needed to implement the two argument version. This is what it took to make it work (the commented lines are the important ones), perhaps this could be clearly documented or streamlined somehow?
import {MockProxy, mockReset} from 'jest-mock-extended';
import Fingerprint2 from 'fingerprintjs2';
jest.mock('fingerprintjs2');
type FingerprintCallback = (data: Fingerprint2.Component[]) => void;
// Signature for `Fingerprint2.get` to mock (we want the one with two args)
type FingerprintGetWithTwoArgs = (
opt: Fingerprint2.Options,
callback: FingerprintCallback
) => void;
const MockFingerprint2 = Fingerprint2 as MockProxy<typeof Fingerprint2>;
// Reset the mock before each test to remove any custom implementations
beforeEach(() => mockReset(MockFingerprint2));
it('passes generated fingerprint to callback', () => {
const testData = [{key: 'foo', value: 'bar'}];
// Cast the mocked function to the signature we want and assign our own `jest.fn`
(Fingerprint2.get as FingerprintGetWithTwoArgs) = jest.fn(
(opt: Fingerprint2.Options, callback: FingerprintCallback) => {
callback(testData);
},
);
expect.assertions(1);
Fingerprint2.get({}, (data: Fingerprint2.Component[]) => {
// Ta-da! We got the two-argument version to pass our test data back
expect(data).toBe(testData);
});
});
The gist is that you cast your mocked function as the signature you want, then assign it as a jest.fn
or something
from jest-mock-extended.
are we still not able to use jest for overloaded methods? can someone help with a demo code for any work-around?
from jest-mock-extended.
I should mention that I only realized this because the type of Fingerprint2.get
was this beast:
CalledWithMock<void, [(components: Component[]) => void]> & {
(options: Options, callback: (components: Component[]) => void): void;
(callback: (components: Component[]) => void): void;
}
You can see the CalledWithMock
that provides mockImplementation
is for the one argument signature, but the type intersects with the two-argument function so you can cast to that
from jest-mock-extended.
Wow... I tried to add undefined
as the second parameter and it worked. But I feel like it should be clear in tests that the the tested code is calling one function and not the other, and currently it is not.
from jest-mock-extended.
I get the same issue
from jest-mock-extended.
@tpischke-bedag did you switch to a better lib?
from jest-mock-extended.
We are still using the library, but only in a very limited fashion. We've mostly switched to implementing our own simple stubs to avoid these issues.
from jest-mock-extended.
SpotifyAlbumsService
export class SpotifyAlbumsService {
public getAlbum(id: string, adapt: false): Promise<SdkAlbum>
public getAlbum(id: string, adapt: true): Promise<Album>
async getAlbum(id: string, adapt = false) {
this.spotifySdk = SpotifyApi.withClientCredentials(
this.configService.get<string>(Environment.SPOTIFY_CLIENT_ID)!,
this.configService.get<string>(Environment.SPOTIFY_CLIENT_SECRET)!
)
const data = await this.spotifySdk.albums.get(id)
return adapt ? this.adaptersService.albums.adapt(data) : data
}
}
test
test('should create album from external id', async () => {
const getAlbumSpy = (
jest.spyOn(spotifyAlbumsService, 'getAlbum') as unknown as MockInstance<
[id: string, adapt: false],
Promise<SdkAlbum>
>
).mockResolvedValue(sdkAlbumMock)
})
I wish there is a better way to do that...
from jest-mock-extended.
Related Issues (20)
- Observable.of mock interface implementation HOT 2
- Option to have mock methods throw by default HOT 2
- description field for Custom Matcher should be optional HOT 2
- Mocks evaluate to `undefined` when used with expect.anything() or expect.any()
- how to define overridable default mock implementation HOT 3
- Doesn't mock special fn in prisma package
- `.calledWith` ignores plain objects as its condition HOT 2
- Support for TypeScript 5.0 HOT 1
- Required to use calledWith when using TypeScript HOT 2
- Typescript error when using @jest/globals
- Doesn't work if injectGlobals is false HOT 2
- The captor function causes type errors when used with `calledWith`.
- How to deep-compare objects with `calledWith`? HOT 1
- Cannot set mock return value on `toString`
- TypeError: Jest: a transform must export a `process` function.
- How to mock an external package with deepMock HOT 1
- How to compare mock to an object with jest HOT 3
- Extreme slow processing of mocks that are created via the mock() function
- Add support for Jest v30
- Type 'DeepNullable<K>' does not satisfy the constraint 'WeakKey' HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from jest-mock-extended.