Aniruth N
Aniruth N

Reputation: 106

how to mock ngrx store.pipe with specific selector using jasmine spyon

In before each I have created a store spy obj

store = jasmine.createSpyObj<SomeState>('Store', ['pipe', 'dispatch'])

In individual test I want to return a mock for a specific selector. Using withargs doesnt seems to work.

store.pipe.withArgs(select(someSelector1)).and.returnValue(of(someMock))
store.pipe.withArgs(select(someSelector2)).and.returnValue(of(someMock2))

The only way to mock selectors is to use returnvalues and return mock observable in the order they are bring called in source code, like so:

store.pipe.and.returnValues(of(someMock1), of(someMock2))

Another alternative is to use select instead of pipe in source code and spy on store select instead of pipe, like so:

store = jasmine.createSpyObj<SomeState>('Store', ['pipe', 'dispatch', 'select'])

store.select.withArgs(someSelector1).and.returnValue(of(someMock))
store.select.withArgs(someSelector2).and.returnValue(of(someMock2))

but this doesnt work when the selector takes a parameter like this:

store.select.withArgs(someSelector(param)).and.returnValue(of(mock))

Upvotes: 1

Views: 4202

Answers (1)

AliF50
AliF50

Reputation: 18839

If you're using the MockStore, you can have mock selectors like this: https://ngrx.io/guide/store/testing#using-mock-selectors

If you're using the actual store (StoreModule.forRoot()) also known as integration testing, just dispatch the actions that will change the store and you won't have to mock your selectors. Check out integration testing here: https://ngrx.io/guide/store/testing#integration-testing

With integration testing, you can just do store.dispatch(yourAction()) where the action will actually modify the store and then your selectors will work without mocking them.

Upvotes: 1

Related Questions