score:0

I solved it using mount of enzyme.

Testing Code

 import React from 'react';
 import ReactTestRenderer from 'react-test-renderer';
 import { shallow, mount } from 'enzyme'; // helps to handle refs
 import thunk from 'redux-thunk';
 import TestComponent from 'pathtocomponent';

describe('<TestComponent />', () => {   
    it('should render a action model when order is approved', () => {
      const component = mount(
        <TestComponent
         message="sample message" level="success" title="title sample"
        />
      );
      component.instance().componentDidMount();
      expect(component).toBeDefined();
    });

});

Component with Ref:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ReactNotificationSystem from 'react-notification-system';


export default class TestComponent extends Component {
  constructor(props) {
    super(props);
    this.addNotification = this.addNotification.bind(this);
    this.notificationSystem = null;

  }

  componentDidMount() {
    this.notificationSystem = this.refs.notificationSystem;
    this.addNotification();    
  }



  addNotification() {
    let that = this;
    this.notificationSystem.addNotification({
      message: that.props.message,
      level: that.props.level,
      position: 'tc',
      autoDismiss: 4,
      title: that.props.title,
    });
  }

  render() {
    return (<div>
      <TestComponent ref="notificationSystem" />
    </div>);
  }
}

score:2

Relevant issue discussed here

As mentioned this happens as expected because

React test renderer is not coupled to React DOM. It can't "guess" which DOM APIs your component relies on. You need to mock the nodes yourself, as noted in 15.4.0 release notes. I hope this helps!

You can see that your package react-datetime does make use of ReactDOM for some of its inner components.

The suggested solution for third-party components is to mock them yourself with jest

The workaround is simple if you use jest. Just mock the third party component causing issues.

For example:

jest.mock('third-party-button', () => 'ThirdPartyButton');

Put this at the top of your test file.

Now any imports of third-party-button (replace this with your component) will become a string (e.g. ThirdPartyButton) so the component will become a “leaf” in the snapshot, like a div. Of course this won't actually test it, but it makes sense to only test your own code.


Related Query

More Query from same tag