0

I am working on a new project that consist on a backend API and a react/redux frontend app. I am setting up my first test using jest/enzyme/moxios.

My issue is that, when the api server is not running the test returns "Network error", but all test are ok if the server is up.

This is my jest test (CRA):

import React from "react";
import { mount } from "enzyme";
import moxios from "moxios";
import Root from "../Root";
import App from "../App";

beforeEach(() => {
  moxios.install();
  moxios.stubRequest("*/products", {
    status: 200,
    response: [
      {
        id: 0,
        name: "Test product 0",
        description: "Test description 0",
        price: 55.6
      },
      {
        id: 2,
        name: "Test product 2",
        description: "Test description 2",
        price: 55.6
      }
    ]
  });
});
afterEach(() => {
  moxios.uninstall();
});

it("can fetch a list of products and display them", done => {
  const wrapped = mount(
    <Root>
      <App />
    </Root>
  );
  moxios.wait(() => {
    wrapped.update();
    console.log(wrapped.find("li").html());
    expect(wrapped.find("li").length).toEqual(2);
    done();
    wrapped.unmount();
  });
});

It seems like moxios is not working as expected but i couldnt find the reason... i also checked that the axios adapter is moxios:

console.log src/__tests__/productsIntegration.test.js:38
      [Function: mockAdapter]
David
  • 519
  • 2
  • 11
  • It looks like you are doing a full render on the entire app in this test (you might want to split that up into unit tests of the individual components). Have you mocked the response for every network request your app makes when it is rendered? If you missed any `axios` will still make an actual network request. – Brian Adams Jan 08 '19 at 16:01
  • Is a integration test this is the reason why im doing the full render. I just moked the response for /products route, the strange part is that the test works if the server is up... – David Jan 08 '19 at 16:14
  • Does your app make any other server requests besides `/products`? `moxios` is set up to mock requests for `/products` but if your app makes any other requests they will execute as regular network requests which will result in "Network error" if your server isn't running. – Brian Adams Jan 08 '19 at 19:17
  • @brian-lives-outdoors nope just request to /products on componentdidmount, you can check the whole project here: https://github.com/dsolanor/starter-project-19/tree/master/frontend – David Jan 09 '19 at 07:47

0 Answers0