vendredi 22 janvier 2016

React renderToString component unit testing

Background

I am using React starter kit for my react application. Inside the server.js they are rendering component using renderToStaticMarkup and then passing it to Html component which include it using dangerouslySetInnerHTML as you can see here

I am trying to create a unit test for my AboutUs page. But because it was rendered as string inside the html component, the unit test does not work for it because it is unable to find this component

UNIT TEST

/*REACT*/
var React = require('react');
import ReactDOM from 'react-dom/server';
var TestUtils = require('react-addons-test-utils');

/*Components*/
var AboutUsPage = require('../../src/components/AboutUsPage');
var App = require('../../src/components/App');
var Html = require('../../src/components/Html');

/*UNIT TESTING*/
import sd from 'skin-deep';
var expect = require("chai").expect;

describe('AboutUsPage component', function(){
  let tree;
  let aboutElement;
  before('render and locate element', function() {
    const data = { title: '', description: '', css: '', body: '' };
    const css = [];
    const context = {
      onInsertCss: value => css.push(value),
      onSetTitle: value => data.title = value,
      onSetMeta: (key, value) => data[key] = value,
      onPageNotFound: () => statusCode = 404,
    };
    data.body = ReactDOM.renderToString(<App context={context}><AboutUsPage /></App>);
    data.css = css.join('');

    tree = sd.shallowRender(<Html {...data} />);
    aboutElement = tree.dive(['App','AboutUsPage']); //could not find App or AboutUsPage components
  });

  it('it should have text hi"', function() {
    expect(tree.subTree('.htmlHead').text()).to.equal("hi"); //pass
  });
  it('it should have text hello"', function() {
    expect(aboutElement.subTree('.aboutHead').text()).to.equal("hello"); //fail
  });
});

I am using mocha, chai & skin-deep for shallow rendering.

So how to write a unit test for the component which was rendered as string?

Aucun commentaire:

Enregistrer un commentaire