GraphQL - Apollo
- Below is an example of creating a mock Apollo cache. See how the readQuery and writeQuery functions can also be mocked for checking when/if they are called.
- NOTE: if you do not want to mock the cache read/write but instead want to check what is actually written to the cache, you can do so by doing:
- Below are an example mutation and query mock. note that the result must be consistent with the queries/mutations otherwise the mock query/mutation will not work. (See the list at the bottom of this medium article).
- The mock cache and mock queries can then be added to the mock provider. Note that if your schema expects a
__typename field in the result, you will need to add addTypename={true} as a prop to the provider. Otherwise you should add addTypename={false}. Also note that since such requests are async, initally when mounted, queries will be in their loading states. To get to the executed state (represented by the hasLoaded variable in the snippet below) we must take a step forward in the event queue. The npm module waait is good for this. (a setTimeout has been shown to also work for this).
History Object
- Where we use
withRouter from react-router-dom we can mock the history object the following way:
- Where we are not using
react-router-dom we can mock the history object the following way:
Mock All vs Some Imports
- If we want to mock all imports we can simply do:
- if, however, we want to mock only some of the imports from a file and then actually use the other imports, we can do the following:
- NOTE: if
functionB, from above, is called by by functionA (in other words from within the same file) and we are trying to test that call, we will not detect it unless we make sure functionA calls the exported version of functionB (since that is the version of the function that we mock once it is imported into a test file). This can be done as shown in an example of path-to-file.js below:
Mock Wrapper component but Render Children
- If you want to render the children of a wrapping component but not go through the hassle of rendering the wrapping component itself (due to even more setup in your test being required for that).