0
votes

I'm trying to test my React class (using TestUtils, Enzyme and Jest), but because of a few workarounds we've had to put up with, it relies on elements in a server-rendered HTML page -- namely, it grabs certain elements from the DOM in componentDidMount before rendering. For example:

componentDidMount() {
  document.documentElement.classList.add('example');
  this.someOtherFunction(document.getElementsByClassName('my-great-className'))
}

I'd like to test this component, but of course the functions in componentDidMount fail because the server-rendered HTML page does not exist in the tests. Is there a way to mock a specific DOM before rendering the React component?

1

1 Answers

2
votes

You can just set the stuff before you start your test

global.document = {
  documentElement: {
    classList: {
      add: jest.fn()
    }
  }
  getElementsByClassName: jest.fn({id:'id'})
}

In your test you can then just check that add was called with example and that someOtherFunction was called with {id:'id'}. As all test files run in its own sandbox its totally safe to set you document mocks like this.