Simulated web server for testing with Jest

Can I ask a unique question? I have a tool for extracting data from webpages directly, not through APIs. I want to create end-to-end tests for this tool using the Jest library, but I need to ensure the web pages I'm referencing remain consistent. It's almost impossible to guarantee this with online resources.

Would it be a good idea to set up a local web server using express or fastify to serve static HTML pages for testing purposes, shutting it down once the tests are completed? Are there any other methods that are more effective?

I appreciate any advice you can provide. Thank you!

Answer №1

When setting up a mock server, you will need to utilize npm msw. To import it into your frontend, follow these steps:

import {setupServer} from "msw/node";
import {rest} from 'msw'

After importing, you can create a const server within your test function:

const server = setupServer(
    rest.get('/check_signup_email/*', (req, res, ctx) => {
      return res(ctx.json({result: 'ok', emails: []}))
    })
  )
  beforeAll(() => server.listen())
  afterEach(() => server.resetHandlers())
  afterAll(() => server.close())

Remember to close your server after each test and reopen it before the new test to avoid false results from tests being executed on previous variables.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

PHP live data updating: stay current with real-time data updates

I have a functional API that is currently static, but I want it to update periodically and display live data in my HTML code. I'm not sure where to begin. Should I start with Javascript or Ajax? Any guidance would be greatly appreciated. This is my ...

Appwrite error message: Unable to access properties of undefined (looking for 'endpoint')

I am currently working on a project using Appwrite and I have encountered an issue with SDKs. When I use a client-side SDK to interact with the functions of Appwrite Teams, everything works perfectly like this: import { Client, Teams } from "appwrite& ...

Bypassing the "Your connection is not private" error in NodeJS + Express with fetch() using Javascript

Presently, I have a setup with a NodeJS + ExpressJS client-side server that communicates with the back-end server via API calls. However, every time I make a call, I need to manually navigate to the URL of the API back-end server and click on Advanced -> ...

Incorporate the use of OpenLayers into a Vue.js application

Can anyone share their insights on incorporating Openlayers into a Vuejs project? I'm looking to showcase various layers within my Vue app. Thanks in advance! ...

Using onclick events, manipulating innerHTML, and dynamically generating tables

Below is the code snippet: window.onload=function(e){ //Created by Firestar001 var X; var Y; var board=""; var rizzalt=document.getElementById("rezzalt"); var letters = new Array; letters = ["A","B","C","D","E","F","G","H","I","J"]; for(a=0; a<=9 ...

Is it possible to utilize WebAssembly in JavaScript to access the memory of a C struct directly?

Looking at the C code snippet below, there is a struct defined as follows typedef struct { ValueType type; union { bool boolean; double number; Obj* obj; } as; } Value; The ValueType enum used in the struct is defined a ...

AngularJS: Issue with JQuery Slider not Updating Scope Value

I am currently working on a project using AngularJS and I have integrated a jQuery slider into it. However, I am facing an issue where I need to change the value of a select box which is defined in a $scope array, but the functionality is not working as ex ...

Is it secure to store information that impacts component rendering within a JWT payload?

I am currently developing a MERN app where users have various roles, and different components are rendered based on their role in React. In my application, I store a JWT containing the user's ID and role in a cookie, which is then decoded in a global ...

External function does not support jQuery types

In my theme.js file, I currently have the following code: jQuery(function ($) { accordion($) }) const accordion = ($) => ... By placing the accordion function directly into the jQuery function, Typescript is able to assist with the installed jquery ...

What is the process for performing a redirection in Node JS?

I have been working on a task to redirect a page to the home page with the route '/search' upon form submission. Within my submit.html file, there is a form that utilizes the '/submit' post method to submit the form data when the submit ...

Array Filtering Results in an Empty Array of Objects

I'm currently attempting to filter out all objects from the projects array that do not appear in the savedProjects array, but I'm ending up with an empty result. Could it be that I am approaching the filtering process incorrectly? Here's my ...

Communication breakdown between components in Angular is causing data to not be successfully transmitted

I've been attempting to transfer data between components using the @Input method. Strangely, there are no errors in the console, but the component I'm trying to pass the data from content to header, which is the Header component, isn't displ ...

What is the process for using express and Postman to send a PUT request and modify a specific field in MongoDB?

I'm struggling to figure out how to use a MongoDB document's id in the route and manipulate the 'balance' field using Postman. Here's what my code currently looks like: My route: router.put('/:id', async (req, res) =&g ...

The sorting function in Vue data table is not functioning as intended

In my code, I have implemented a v-data-table: <v-data-table :headers="walletInHeaders" :items="filteredByQuantityIncome" class="elevation-1"> <template v-slot:items="props"> <td class=&quo ...

Using Javascript to test a specific item in an asp Listbox

Let's consider a scenario where there is ListBox1 containing the following listitem: <asp:ListItem Value="No.1">No.1</asp:listitem> In addition, we have a label for a test purpose: <asp:Label ID="lblLabel" runat="server" Text="Label ...

Adding information to an Excel spreadsheet using JavaScript

I'm facing a challenge in appending data to an existing Excel file using node.js. I've tried using the xlsx-writestream package with the code snippet below: var XLSXWriter = require('xlsx-writestream'); var writer = new XLSXWriter(&a ...

JSON data cannot be transmitted using AJAX

I created a function that tracks the time spent on a specific page and where the user came from. The data is collected and saved into a JSON object, but I encountered an issue when trying to send this JSON via ajax. Upon successful sending, I receive an em ...

What steps do I need to take to link my form with Ajax and successfully submit it?

Here is my HTML code: {% extends 'base.html' %} {% block content %} <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Create a Recipe ...

Launching the forEach function within an ng-repeat loop was it can be done by

I need to implement a function within the ng-repeat that will convert the value of Qprogress object in my JSON into a percentage. I already have the function written, but I am struggling with how to trigger it. I attempted to use a forEach loop inside the ...

What is the best way to configure a metered subscription plan on Stripe that invoices annually but bills extra fees for overage on a monthly basis

I'm in the process of setting up a subscription system on stripe that includes a plan with 5000 monthly credits for a flat $299 yearly fee. My goal is to charge customers who exceed their monthly credit limit by the end of each month. For example, if ...