Search code examples
javascriptjestjsmockwebserver

Imitate webserver for tests with Jest


I have a bit of a weird question: I have a program for scraping data from webpages (just the actual HTML pages, not API responses).

I need to write end-to-end tests for this program with the Jest library. In order to test the functionality consistently, I need to make sure that the referred web pages don't change, which would be almost impossible to achieve with resources on the web.

I wondered how good of a practice it is to spin up a new webserver locally with express/fastify/etc. to serve static HTML pages before running the tests and then shut the server down once the tests pass.

What I am looking for is a light web server with a single task - serve static html+css pages. Are there any better ways to achieve what I mentioned? Thank you in advance!


Solution

  • We run E2E on our dev server EG:- https://dev.something.com, which is always up and running. Also as you said you could launch a lightweight webserver on localhost to run tests. But the only problem is When you do E2E using CI/CD pipelines, Then the test server can't access localhost. In that situation, you need a separate server to serve the site to the test server.

    For now, If You are considering running tests on the local machine by launching and stopping a web server, I suggest you to use the live server extension in visual studio code. That is extremely lightweight and the best option to serve HTML and asserts. It will launch your site on localhost, Once your job is done, You can stop it with a button click.

    Live Server (VS Code Extension)