【发布时间】: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
});
});
我正在使用mocha、chai 和skin-deep 进行浅层渲染。
那么如何为呈现为字符串的组件编写单元测试呢?
【问题讨论】:
标签: javascript node.js unit-testing reactjs mocha.js