I have a page that has the headline and the different magical beast. And then I can also see what's actually returned there. So through the API from story block, I get the actual content that I can then use to show my content, the same for the more specific pages. So I have a magical beast and then I have some content here that shows all the details of that magical beast.
All right. So let's start. The first thing for making a mock service worker setup is that you actually need some kind of API, you need some kind of asynchronous way of interaction. So in my example, I have a component that fetches, just does a simple fetch to Storyblocks API and that has all the responses. And then from that response, I build the actual page that we see. And the important part here is that now we need to mock the API. So our first step is to actually create a mock directory. In the root of our project, it could also be somewhere else, but I will do it in the root. And then we set up the mock service worker.
So what do I mean with a mock directory? If we look into the example, we have a folder there that's called mocks. And then we have two JSON files. So we have the beast JSON, that's the start page. And then we have the niffler JSON, that's a mock of the actual, more specific page. How can you get those JSONs? The simplest thing is to have your application, and then check in the network what is actually being returned by the API. So if we reload that, my mock here is basically this request and this response we have here. So the story, I could just copy that and paste that here into my beast JSON file. So this one is just a copy of what I had on that page. So that's really the first part, to have some mocks that can be used by the mock service worker, but also by other unit tests that might not need the mock service worker.
Then the next step is to actually set up mock service worker and to set up some handlers. So for setting up the mock service worker, we need to actually create a setup file. So in the white disk config, we can configure some setup files. So you will provide the path to the file that is setting up our testing environment. Then here in test setup, I have this index.js file that has my global testing setup. So that's the setup that is used in all the tests that I'm writing. I also have some other stuff here, but the important part is here, the mock service worker setup file, where I connect mock service worker with YDist. So before all, after all, and after each test, we're starting the server, we're closing the server, and then we're resetting the handles after each test.
Comments