Testing non-mutating Effects from Environment?

In writing tests, I have some Effects that don't mutate my state. That is, I have a 'DataClient' environment object that persists some data to my database and is mocked to not do anything (return .none) during testing:

environment: TopShowsEnvironment(dataClient: DataClient.mock(
                    setFavorite: { _,_ in return .none }
                ))

But when I test a particular app action, I just want to make sure that my dataClient function is called. Any suggestions for best approach? Thanks.

1 Like

Yeah there is a good pattern for this. You just need to hold onto a bit of mutable state in your test, mutate it inside the stubbed effect, and then assert on it in .do { } block.

For example, this shows how to do it.

First we set up a mutable boolean that determines if the requestWhenInUseAuthorization method was invoked on the location manager:

var didRequestInUseAuthorization = false

Then the mock stubs out that endpoint with:

requestWhenInUseAuthorization: { _ in
  .fireAndForget { didRequestInUseAuthorization = true }
}

And finally to verify that effect was invoked you can do an XCTAssert inside a .do block:

.send(.currentLocationButtonTapped) {
  $0.isRequestingCurrentLocation = true
},
.do {
  XCTAssertTrue(didRequestInUseAuthorization)
},

Let me know if that works for your use case.

2 Likes

Yeah, that's a great and simple pattern, thanks!

Terms of Service

Privacy Policy

Cookie Policy