How to test lasValueFrom response and don't get message:'no elements in sequence' name:'EmptyError'

Viewed 364

I'm trying to test the emptyBasket method and since I upgraded the deprecated toPromise() to lastValueFrom() (rxjs 7.1.0) and I only get the error:

message:'no elements in sequence'
name:'EmptyError'

Method under test:

    emptyBasket(): Promise<void> {
    return lastValueFrom(this.shoppingClient.emptyBasket()).then(() => this.store.dispatch(new EmptyBasket()));
}

Test:

it('should call emptyBasket on shoppingClient', (done) => {
            mockStore.dispatch = jest.fn();
            shoppingClientMock.prototype.emptyBasket = jest.fn().mockReturnValue(of());

            service.emptyBasket().then(() => {
                expect(shoppingClientMock.prototype.emptyBasket).toHaveBeenCalledTimes(1);
                expect(mockStore.dispatch).toHaveBeenCalledTimes(1);
                expect(mockStore.dispatch).toHaveBeenCalledWith(new EmptyBasket());
                done();
            },
            (err) => { 
                console.log('error', err)
                done();
        }
            );
        });

Does anybody know how to workaround this problem?

Many thanks!

1 Answers

This first thing I've noticed is this line:

shoppingClientMock.prototype.emptyBasket = jest.fn().mockReturnValue(of());

When you use just of() is an equivalent of using EMPTY. In other words, it just emits complete notification and that's it. However, lastValueFrom() returns a Promise and a Promise needs to be resolved with a value (that's one of the core differences between RxJS Observales and Promises). So the error is correct.

You should force it to return a value with for example of(undefined) or of(void 0) even when the value doesn't matter.

Related