4

This question is similar to this previous one I opened. But now I'm using a different framework, Jest.

My code goes like this:

import * as React from "react";
import * as ReactDOM from "react-dom";

import * as injectTapEventPlugin from "react-tap-event-plugin";

import Application from "./components/Application";

import "./assets/styles/theme.css";

injectTapEventPlugin();

ReactDOM.render(<Application />, document.getElementById("root"));

There's 3 things that I'd like to test here:

  1. injectTapEventPlugin() was called.
  2. ReactDOM.render was called with the expected arguments, <Application />, and document.getElementById("root"), respectively.
  3. That ./assets/styles/theme.css was imported. I know this one is weird but this import is here so that webpack picks it up and includes it in the final bundle. Maybe this import shouldn't exist and I should make sure that theme.css file is lodaded in some other way.

At least 1 and 2 needs to be tested I think... Jest uses Jasmine2 and I'm also using Enzyme (but that probably doesn't help here).

Any help is appreciated :)

Community
  • 1
  • 1
rfgamaral
  • 16,546
  • 57
  • 163
  • 275

1 Answers1

1

The problem for testing this, is that the module only import stuff but does not export anything, which makes it hard to test. So the first question you should ask yourself is "Why do I need to test this". Cause the only think that happens here are 2 function calls.

Testing #1 is easy, mock the module with a spy, import it into the test and check the spy was called

import * as injectTapEventPlugin from "react-tap-event-plugin"; 
jest.mock('react-tap-event-plugin', ()=>jest.fn())

expect(injectTapEventPlugin).toHaveBeenCalled()

Not sure if the import * as syntax is a problem in this case.

For testing #2 I'm not sure if its even possible to test as you have no way to mock document.getElementBy as it is called before you could overwrite it in the test.

Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
  • Yeah, I had to call `jest.mock` before the import otherwise it wouldn't work. But you're right, I probably don't need to test this... I mean, if I don't call `injectTapEventPlugin` or `ReactDom.render` correctly, the app will simply not work... And this is file that it's most likely to not change much in the future. As long as every component is tested, this file is just like "hey, render the app" and that's it. – rfgamaral Jan 27 '17 at 11:23