I have a controller which used rxjs' lastValueFrom method, and I want to mock the method so that the actual method won't be called. My code for the controller is:
async doSomething(request) {
...
const data = await lastValueFrom(
...
);
...
}
For the test, I've tried multiple ways, which is:
import rxjs from 'rxjs';
jest.spyOn(rxjs, 'lastValueFrom').mockReturnValueOnce(
new Promise((resolve, reject) => {
resolve(true);
}),
);
// This gives me error: Cannot spyOn on a primitive value; undefined given
import { lastValueFrom } from 'rxjs';
lastValueFrom = jest.fn().mockReturnValueOnce(
new Promise((resolve, reject) => {
resolve(true),
);
// This gives me error: Cannot assign to 'lastValueFrom' because it is an import.
import rxjs from 'rxjs';
rxjs.lastValueFrom = jest.fn().mockReturnValue(
new Promise((resolve, reject) => {
resolve(true);
}),
);
// This gives me error: Cannot set property 'lastValueFrom' of undefined
If you're using TypeScript I'm afraid the only way is mocking the import 'rxjs'.
jest.mock('rxjs', () => {
const original = jest.requireActual('rxjs');
return {
...original,
lastValueFrom: () =>
new Promise((resolve, reject) => {
resolve(true);
}),
};
});
import { of, lastValueFrom } from 'rxjs';
test('test', () => {
lastValueFrom(of(1)).then((val) => {
expect(val).toStrictEqual(true);
});
});
Live demo: https://stackblitz.com/edit/node-6vjbxb?file=index.spec.ts
With just ES* seems like you could do: How to spy on a default exported function with Jest?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With