'Jest test error: ...subscribe is not a function
I'm using Jest to test my Angular app (using Nx workspaces). I have a component that uses a service that I'm trying to mock. Here's the code:
myDummyService.permissions$.subscribe(permission => return // whatever);
In my test I mock the service like this:
myDummyServiceMock = {permissions$: jest.fn()}
But when the test runs and the constructor is invoked I get the following error:
`myDummyService.permissions$.subscribe is not a function`
I can't mock the subscribe function, so how can I get around this error? I tried this but I don't think it's right:
myDummyServiceMock = {permissions$: jest.fn(), subscribe: jest.fn()}
And if I do this then it works, but is it bad form?
myDummyServiceMock = {permissions$: of(true)}
Solution 1:[1]
first of all permission$ is a property, not a function, secondly, it should be an observable. Therefore it should be defined properly, for example with help of EMPTY from rxjs.
myDummyServiceMock = {permissions$: EMPTY};
Now it has subscribe, pipe and other methods.
If you want to manipulate its emits, you can use a Subject instance instead of EMPTY.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | satanTime |
