【问题标题】:React renderToString component unit testingReact renderToString 组件单元测试
【发布时间】:2016-03-23 17:23:47
【问题描述】:

背景

我在我的反应应用程序中使用React starter kit。在server.js 内部,他们使用renderToStaticMarkup 渲染组件,然后将其传递给Html 组件,该组件使用dangerouslySetInnerHTML 包含它,如您所见here

我正在尝试为我的AboutUs 页面创建一个单元测试。但是因为它在 html 组件中被渲染为字符串,所以单元测试对它不起作用,因为它无法找到这个组件

单元测试

/*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 because it was in html component
  });
  it('it should have text hello"', function() {
    expect(aboutElement.subTree('.aboutHead').text()).to.equal("hello"); //fail because it was in aboutus component
  });
});

我正在使用mochachaiskin-deep 进行浅层渲染。

那么如何为呈现为字符串的组件编写单元测试呢?

【问题讨论】:

    标签: javascript node.js unit-testing reactjs mocha.js


    【解决方案1】:

    这不是单元测试。考虑一下您真正要测试的内容。是AboutUsPage服务端渲染的完整集成测试,还是AboutUsPage单元测试?

    如果您只想测试 AboutUsPage,请对其进行测试,并且不要将其余组件带到聚会上。这就是单元测试 - 测试单个代码单元。所以不是

    tree = sd.shallowRender(<Html {...data} />);
    

    随便用

    tree = sd.shallowRender(<AboutUsPage />);
    

    并在 tree 上执行与 AboutUsPage 相关的断言。

    但是,如果您想测试整个链,则有多种选择。您已经在 data.body 中获得了渲染的标记字符串,因此您可以随时进行一些字符串操作并检查它是否包含您要查找的内容。更好的选择可能是使用像 jsdom 这样的工具,它使您能够在 Node 环境中对 DOM 进行操作,并使用普通的 DOM 选择器来运行您的断言。

    如果您真的想在“真实”环境中进行测试,请使用 PhantomJS 运行您的测试,这是一个可以与一大堆测试框架 (http://phantomjs.org/headless-testing.html) 一起使用的无头浏览器。

    【讨论】: