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