How to reassign value from mockStore.overrideSelector()?

Viewed 654

I have a selector that returns a boolean. For my unit test I need to test when this value is true and false.

By default, in the test setup, I have the following:

mockStore.overrideSelector(someSelector, true);

I need to change the value from the selector to false, however when I try the following:

mockStore.resetSelectors();
mockStore.overrideSelector(someSelector, false);
mockStore.refreshState();
spectator.detectChanges();

The selector is still returning true.

How can I reassign a value previously set from overrideSelector method?

1 Answers

As mentioned in the official docs Ngrx Testing

To update the mock selector to return a different value, use the MemoizedSelector's setResult() method. Updating a selector's mock value will not cause it to emit automatically. To trigger an emission from all selectors, use the MockStore.refreshState() method after updating the desired selectors.

So something like this should work...

const mockSelector = mockStore.overrideSelector(someSelector, true);
...
...
mockSelector.setResult(false);
mockStore.refreshState();

If the selector returns an object rather than a primitive like true or false, refreshState only seems to detect that you've changed the value if you return a copy of the object, rather than the original object.

const obj = { foo: 'bar' };
mockStore.overrideSelector(objSelector, obj);
...
...
obj.foo = 'baz';

// INCORRECT; selector won't emit again
// mockSelector.setResult(obj);

// CORRECT; make a deep copy of the object
mockSelector.setResult(JSON.parse(JSON.stringify(obj)));

mockStore.refreshState();
Related