FujoWebDev / AO3.js

NodeJS API for scraping AO3 data
MIT License
15 stars 8 forks source link

chore(tests): add msw for mocking api http requests #19

Closed jakehamilton closed 2 years ago

jakehamilton commented 2 years ago

This PR adds MSW, but you'll also notice one or two other things that were touched while I was working on this.

First, here's a rundown of the little stuff:

  1. .editorconfig

The settings on editors tend to differ and cause issues when things get auto-formatted. I added an EditorConfig file so that things get autoconfigured and contributors don't have to worry about updating their editor settings when working on the project.

  1. src/utils/user.ts

There was a bug where the class .userstuff existed in multiple places on the page. I updated the selector to look for .bio .userstuff which should always only get the actual bio. However, when saving the file it got hit by the formatter. However, it should now be in line with the other code in the codebase. Though, let me know if you'd like me to revert this :P

Now, on to how MSW is setup to work:

Jest is now configured to load a setup file jest.setup.js. This file configures MSW to start up, handle requests for each test, and then shutdown at the end of testing.

The MSW server lives in src/mocks/server.js. Really all that happens there is that it creates an MSW server using the handlers defined in src/mocks/handlers/*.

Handlers! MSW can mock REST calls pretty easily. To do so, you call msw.rest.METHOD where the METHOD is an http method like get, put, and so on. For now, I have this set to rest.all which will handle every method since I wasn't sure of some of the internals of the library. If these are only ever GET requests, then we can swap this to rest.get pretty easily.

The responses that the handlers return are stored in src/mocks/data. I've gone through each resource that was being tested against and saved a copy of the request in the appropriate directory. Here's an example of this:

# Make a directory to save responses in.
mkdir -p './src/mocks/data/tags/Original Senator Characters'

# Save the response to a file in the directory.
# Note the "-L" option at the end of the command which ensures we follow redirects.
curl 'https://archiveofourown.org/tags/Original%20Senator%20Characters/works' -o './src/mocks/data/tags/Original Senator Characters/works.html' -L

With the handlers created and the data saved, each handler can dynamically load the appropriate cached response and reply with it.

Finally, I'd like to point out the src/mocks/handlers/all.js handler. I've added this as a catch-all which makes it easier to recognize when something isn't mocked and surfaces the URL associated. If you ever see this in the future, that means you'll need to add a cached copy of the resource.

resolves #16