zendesk / laika

Log, test, intercept and modify Apollo Client's operations
https://zendesk.github.io/laika
Apache License 2.0
122 stars 7 forks source link

Feature request: Provide a way to simulate network delay in mock responses #56

Open kgoggin opened 1 year ago

kgoggin commented 1 year ago

Use Case: I'd like to be able to write a test to simulate an async/delayed response from the GraphQL server. This would be similar to enabling "network throttling" in Dev Tools to test what happens when it takes a while for the server to respond, and would be useful for testing things like race conditions that pop up when certain queries finish before others.

Implementation Options

  1. Allow for returning a Promise from the ResultFn type. Laika waits for the Promise to resolve before returning the mocked result.
  2. Allow for specifying a delay in the mock configuration, and Laika automatically handles making it async.

I think both options would be useful, honestly. The first one would be great for unit tests, so you could manually resolve the promise whenever you were ready vs. specifying an arbitrary amount of time. But, the second one would be nice for less boilerplate code when all you want is to make your test behave a little more like a real server.

niieani commented 1 year ago

Option 1 should be pretty easy. Here, we can check if mockedResult is a Promise, and then if it is, we run the rest of that code in a .then(...). Maybe we wanna also .catch() and push the error to the Observable.

danielvanmil commented 1 year ago

+1

danielvanmil commented 1 year ago

can this also be implemented by using the keepNonSubscriptionConnectionsOpen? I cannot seem to get it to work with something like:

const subscriptionInterceptor = laika.intercept({operationName: "GetUser"}, false, true);
subscriptionInterceptor.waitForNextSubscription().then(() => {
  window.setTimeout(() => {
   // subscriptionInterceptor.fireSubscriptionUpdate also doesn't do the job?
    subscriptionInterceptor.mockResult({
      result: {data: {user: aUser()}},
    });
  }, 2000);
});

Also

niieani commented 1 year ago

@danielvanmil I don't think waitForNextSubscription will work for non-subscription operations. You could try just pushing the update with fireSubscriptionUpdate. But ideally this would be added to Laika itself.

danielvanmil commented 1 year ago

@niieani : thanks for the answer, but I still don't understand it. I notices the keepNonSubscriptionConnectionsOpen option and thought I could use this to delay a query or mutation response just like I can respond to subscriptions.

What is the use case of keepNonSubscriptionConnectionsOpen and can it be used to delay a response? (otherwise I don't understand what it can be used for?

Is it possible to provide a nice exampe, test or doc?

Thanks and keep up the great work!