I have the following simple sample React app the frontend of which runs on port 5000 and the backend Express server runs on port 5001. The relationship between the two is established via "proxy": "http://localhost:5001",
in package.json.
On the frontend, if "Submit" is clicked, it sends a POST request to /sample
route of the backend and prints the status (200) to the screen. This all works fine.
I would now like to test this behavior with react-testing-library (or any other similar package). I have set up the following test file; however, when it runs, I get Error: connect ECONNREFUSED 127.0.0.1:80
. It is almost if the testing library is not looking in the correct place for the backend? Is there a way to specify this in a config?
I saw some other posts with this error, they advise to include a leading "/" at front of the URL, but I already have this in my case (i.e. /sample/). Jest test passed but get Error: connect ECONNREFUSED 127.0.0.1:80 at the end
Frontend
function App() {
const [responseStatus, setResponseStatus] = useState<number>();
const { handleSubmit, register } = useForm();
const onSubmit = (data: any) => {
console.log(data);
fetch('/sample/', {
method: 'POST',
body: data,
}).then((resp) => setResponseStatus(resp.status));
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<p>Welcome</p>
<p>{responseStatus}</p>
<input {...register('fieldNo1')} />
<button type="submit" data-testid="submit-button">
Submit
</button>
</form>
);
}
Express backend
var router = express.Router();
router.post('/', function (req, res, next) {
res.sendStatus(200);
});
Test file
test('sample test', async () => {
render(<App />);
const welcomeText = screen.getByText('Welcome');
expect(welcomeText).toBeInTheDocument();
const submitButton = screen.getByTestId('submit-button');
fireEvent.click(submitButton);
const responseText = await screen.findByText('200');
expect(responseText).toBeInTheDocument();
});
package.json
{
"name": "sample",
"version": "0.1.0",
"private": true,
"proxy": "http://localhost:5001",
"dependencies": {
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.1.1",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.4.1",
"@types/node": "^16.11.27",
"@types/react": "^18.0.6",
"@types/react-dom": "^18.0.2",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-hook-form": "^7.33.1",
"react-scripts": "5.0.1",
"supertest": "^6.2.3",
"typescript": "^4.6.3",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "set PORT=5000 && react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@types/supertest": "^2.0.12"
}
}