Skip to content

Testing with a Proxy #4127

Closed
Closed
@mattcarlotta

Description

@mattcarlotta

Is there a way to extend a package.json proxy to a testing ENV without ejecting CRA? Or, should I remove the proxy and hard code all API calls? Or should I just mock all the API calls?

Currently using a proxy in my package.json to make API calls to a running local server:

"proxy": {
  "/api/*": {
   "target": "http://localhost:5000"
  }
},

In one of my components, I'm creating an API call to retrieve a list of subscribers:

  axios.get('/api/subscribers') // http://localhost:5000/api/subscribers
    .then(({data: {subscribers}}) => {
      console.log('these are subs', subscribers);
      this.setState({ subscribers })
    })
    .catch(err => {
      console.log('server err:', err);
      this.setState({ serverError: err })
    })

While this works fine within the app and in the browser, when running jest+enzyme tests, /api/subscribers resolves to http://localhost:80:

server err: { Error: connect ECONNREFUSED 127.0.0.1:80
  at Object._errnoException (util.js:1024:11)
  at _exceptionWithHostPort (util.js:1046:20)
  at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1182:14)
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
   port: 80,

Subscribers.test.js

import React from 'react';
import { shallow } from 'enzyme';
import Subscribers from '../../../../containers/subskribble/subscribers/Subscribers';
import axios from 'axios';
import httpAdapter from 'axios/lib/adapters/http';

axios.defaults.adapter = httpAdapter; // required for Axios, otherwise network error

describe('[SUBSCRIBERS]', () => {
  it('should render Subscribers component', () => {
    const wrapper = shallow(<Subscribers />);
    expect(wrapper).toMatchSnapshot();
  })

 //  it('should fetchAllSubscribers from API', () => {
    // return axios.get('/api/subscribers').then(({data: {subscribers}}) => // 
       // expect(subscribers).not.toEqual(undefined))
  // })

})

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions