score:3

Accepted answer

It's happening because in your test environment you're not initiate the firebase app (using initializeApp) and you probably shouldn't (you don't want to communicate with firebase every time you run a test, especially not unit tests). This kind question also applies to other external services like your own server and external APIs.

So how can you test your app?

The answer is mocking - supply an alternative implementations for those services to the tests environment. There are some kind of mocking, depends on what and how you want to mock. Also, sometimes, the tools supply their own testkit (which, again, supply a testable implementation for the methods it expose).

In this case, you can use jest mocking mechanizm to mock the response from firebase so your app "doesn't know" it received the data from other resource, and will act like it should.

The relevant jest methods are spyOn and mockImplementation, and here is an example (I simplified your component):

App.spec.js

test("mount", async () => {
  const fetchPromise = Promise.resolve([{ name: "order1" }]);
  jest.spyOn(firebase, "app").mockImplementation(() => ({
    firestore: () => ({
      collection: () => ({
        get: () => fetchPromise
      })
    })
  }));
  let wrapper = mount(<App />);
  await fetchPromise;
  wrapper.update();
  expect(wrapper.find("span").text()).toBe("order1");
});

App.js

export default class App extends React.Component {
  state = {
    orders: []
  };

  fetchOrders() {
    try {
      app()
        .firestore()
        .collection(DATABASE_COLLECTION_ORDERS)
        .get()
        .then((snapShot) => {
          this.setState({ orders: snapShot });
        });
    } catch {
      console.log("do nothing");
    }
  }

  componentDidMount() {
    this.fetchOrders();
  }

  render() {
    return (
      <div className="App">
        {this.state.orders.map((order) => (
          <span key={order.name}>{order.name}</span>
        ))}
      </div>
    );
  }
}

https://codesandbox.io/s/enzyme-setup-in-codesandbox-forked-jyij5?file=/src/App.js:133-730 (Click on the Tests tab)


Related Query

More Query from same tag