📜  jest cross origin localhost fobbiden - Javascript (1)

📅  最后修改于: 2023-12-03 15:32:06.729000             🧑  作者: Mango

Jest Cross Origin Localhost Forbidden - Javascript

Introduction

If you're a javascript developer using Jest for testing, you may run into an issue where Jest complains about Cross Origin issues when trying to fetch data from a localhost server. This error can occur when running your Jest test suite and causes failures in your test cases. In this article, we will discuss what this error means, why it happens, and how to fix it.

What does this error mean?

Jest is a javascript testing framework that allows developers to write test cases for their code. When running a test suite, Jest attempts to fetch data from a specified server in order to test the functionality of the code being tested. However, when the server is running on localhost and Jest is running on a different port, Jest will run into a Cross Origin issue.

Why does this error occur?

Cross Origin errors occur when a website or app attempts to access resources or data from another domain. In this case, Jest is attempting to access data from a local server that is running on a different port. This violates the Cross Origin policy, causing Jest to fail.

How to solve this issue?

There are a few ways to solve the Cross Origin issue when running local servers and Jest. The most common solutions are:

Solution 1: Use Jest's testEnvironment configuration

Jest has a configuration option called testEnvironment that allows developers to specify the environment their tests are being run in. By default, Jest uses the jsdom environment, which simulates a browser environment for your tests. However, this environment doesn't allow cross-origin requests.

To solve this issue, you can switch to a different environment that supports cross-origin requests. One such environment is node, which allows you to use Node.js' http library to create a server and listen for requests. Here's an example of how to set up your jest.config.js file to use the node environment:

module.exports = {
  testEnvironment: 'node',
};
Solution 2: Set up a proxy server

Another solution to this issue is to set up a proxy server that can redirect requests to your local server. This allows Jest to access the data it needs without violating the Cross Origin policy. One popular proxy server is http-proxy-middleware, which can be installed via npm.

Here's an example of how to set up a proxy server in your Jest test suite:

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = {
  setupFiles: ['<rootDir>/setupTests.js'],
  ...
  proxy: {
    '/api': {
      target: 'http://localhost:3000',
      changeOrigin: true,
      pathRewrite: { '^/api': '' },
      router: {
        'localhost:8000': 'http://localhost:3000',
      },
      onProxyRes(proxyRes, req, res) {
        proxyRes.headers['Access-Control-Allow-Origin'] = '*';
      },
    },
  },
};
Solution 3: Use a CORS plugin

If neither of the above solutions works for you, you can try using a CORS (Cross Origin Resource Sharing) plugin. CORS plugins add the necessary headers to HTTP responses, allowing cross-origin requests to succeed. One popular CORS plugin is cors-anywhere, which can be installed via npm.

Here's an example of how to use cors-anywhere to solve the Cross Origin issue in your Jest tests:

const axios = require('axios');

const instance = axios.create({
  baseURL: 'https://cors-anywhere.herokuapp.com/http://localhost:3000/api/',
  headers: { 'X-Requested-With': 'XMLHttpRequest' },
});

describe('My test suite', () => {
  test('should fetch data from local server', async () => {
    const response = await instance.get('/users');
    expect(response.status).toBe(200);
  });
});
Conclusion

The Cross Origin Localhost Forbidden error in Jest is a common issue when running Jest and local servers. However, with the solutions outlined above, you can easily solve this issue and continue testing your code. By using Jest's testEnvironment configuration, setting up a proxy server, or using a CORS plugin, you can successfully test your code and ensure its functionality.