😜 mocking gatsby
I recently started adding Jest tests to all of my Gatsby projects. Right off the bat I didn't know how to mock gatsby
so that I could test components that performed graphql
calls with useStaticQuery
.
I went searching on the Gatsby site and found some documentation showing how to mock gatsby
. The documentation suggested to use jest
manual mocks, which call for a __mocks__
directory placed next to the module to be mocked. But I hated the thought of having an ugly __mocks__
directory at the root of my project.
So I kept digging until I found this example in the jest
documentation. The example showed me that the jest.mock()
function takes a second argument which can output any object used to mock the module!
The result is a fairly simple gatsby
mock that I placed in my test setup file.
And don't forget to tell jest
to run your setup file in jest.config.js
.
If you're looking for more context, you can check out the repository for this site where I implemented this mock. Do you test your Gastby sites? If so, share your testing tips with me on Twitter!