Welcome to my blog π. I hope you are all safe and that this blog finds you in good health β€οΈ.
In my previous blog, we have learnt to mock GraphQL using Jest.mock(). Please click here if you have missed it.
In this blog, Let's learn about mocking graphql queries using Apollo Mocked Provider.
Mocking GraphQL Queries using Apollo Mocked Provider
Recap
We have a Basic Application running which displays the list of countries along with the capital city. Please refer to the Repo link for more information.
Mocked Provider
So, let's use the same Application and run our test cases using Apollo Mocked Provider.
Mocked Provider is one of the best practices to test React Components that use Apollo Client.
We use Apollo Provider for GraphQL in the Application Code and similar to that Mocked Provider for mocking GraphQL and removes the external dependency of communicating with your Server.
Mocks consist of an Array of Requests and respective results for the GraphQL API calls.
That's it folks for running our Test case successfully.
Test case
PASS src/App-using-mocked-provider.test.jsx
App test
β renders learn react link (58 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.724 s, estimated 1 s
Ran all test suites related to changed files.
Watch Usage: Press w to show more.
We can also pass different responses for different requests and test your Application end to end.
Now let's analyse whether we can handle our challenges faced using jest.mock()
Use case - 1: We have a react component that has 2 different API calls to be made to the server.
Yes, we can handle it easily by passing different Results for different APIs and also test if we are passing exact params and getting proper results.
Use Case - 2: We have a react component that has type-in search functionality.
Even this can be tested easily such as we have type in search and we wanted to test whether for each type in letter, Are we getting the expected response
Typein
This way we have handled the 2 challenges which we faced while we used jest.mock().
Now let's get to know some challenges.
Challenges
There are not many challenges when we use MockedProvider but only one cautious thing about it is We have to be very careful with the variables in the request if you input "searchCountry" as 'Li' and you missed adding this in the mocks then your test case will be failed.
So, Be Aware of the variables while you add your requests.