简体   繁体   English

使用.jsx扩展名测试React组件

[英]Testing React components with a .jsx extension

I am new to the React framework and right now I am exploring the way to test components in React. 我是React框架的新手,现在我正在探索测试React中组件的方法。 I was following this example: https://www.codementor.io/reactjs/tutorial/test-reactjs-components-karma-webpack for setting up a unit testing framework for React using mocha and karma. 我正在关注以下示例: https://www.codementor.io/reactjs/tutorial/test-reactjs-components-karma-webpack : https://www.codementor.io/reactjs/tutorial/test-reactjs-components-karma-webpack ,用于使用mocha和karma为React设置单元测试框架。

I realized that all my components had .jsx extensions and not .js, and I dug deeper. 我意识到我所有的组件都具有.jsx扩展名而不是.js,因此我进行了更深入的研究。 I understood the components need to be built before they could be imported/used. 我知道必须先构建组件,然后才能导入/使用它们。

I tried using this example: http://www.bebetterdeveloper.com/coding/getting-started-react-mocha.html . 我尝试使用以下示例: http://www.bebetterdeveloper.com/coding/getting-started-react-mocha.html : http://www.bebetterdeveloper.com/coding/getting-started-react-mocha.html But this does not cover karma. 但这不包括业障。

How do I use karma so that the jsx files are built and then imported? 我如何使用业力,以便先生成jsx文件,然后将其导入?

I am using gulp for building the artifacts and my NodeJS version is 5.6 我正在使用gulp构建构件,我的NodeJS版本是5.6

Here's a simple example for unit testing React components using Mocha, Chai, and a jsdom helper, which is used in place of a test runner like Karma. 这是一个使用Mocha,Chai和jsdom helper来对React组件进行单元测试的简单示例,用于代替像Karma这样的测试运行器。

You will need the following dependencies: 您将需要以下依赖项:

"dependencies": {
  "react": "^15.1.0",
  "react-dom": "^15.1.0"
},
"devDependencies": {
  "babel-preset-es2015": "^6.9.0",
  "babel-preset-react": "^6.11.1",
  "babel-register": "^6.9.0",
  "chai": "^3.5.0",
  "jsdom": "^9.3.0",
  "mocha": "^2.5.3"
}

It's also useful to have an npm script that points to mocha - npm run test will execute your tests: 拥有一个指向mocha的npm脚本也很有用npm run test将执行您的测试:

"scripts": {
  "test": "./node_modules/.bin/mocha"
},

After you have your dependencies set up, you'll want a directory structure that looks like this: 设置依赖项后,您将需要一个如下所示的目录结构:

.
├── /src
│   └── component-to-test.js
├── /test
│   ├── /unit
│   │   └── component-to-test.spec.js
│   ├── /util
│   │   └── jsdom.js
│   └── mocha.opts
├── .babelrc
└── package.json

We'll start off with your .babelrc file. 我们将从您的.babelrc文件开始。 You'll need Babel to transpile your JSX into JavaScript. 您需要Babel才能将JSX转换为JavaScript。 If you want to use ES6 syntax (highly recommended), Babel will help with that too. 如果您想使用ES6语法(强烈建议使用),Babel也会提供帮助。 I've included both of these presets in the devDependencies. 我已经将这两个预设都包含在devDependencies中。

.babelrc: .babelrc:

{
  "presets": ["es2015", "react"]
}

Next, we'll look at the jsdom helper. 接下来,我们来看一下jsdom助手。 This is needed in order to render React components into an in-memory DOM, which is typically handled by a test runner like Karma. 为了将React组件呈现到内存中的DOM中,这是必需的,通常由像Karma这样的测试运行者来处理。

jsdom.js: jsdom.js:

(function () {
    'use strict';

    var jsdom = require('jsdom'),
        baseHTML,
        window;

    if (!global.window) {
        baseHTML = '<!DOCTYPE html><html><head lang="en"><meta charset="UTF-8"><title>Tests</title></head><body></body></html>';
        window = jsdom.jsdom(baseHTML).defaultView;

        global.window = window;
        global.document = window.document;
        global.navigator = window.navigator;
    }

}());

In order to leverage this jsdom helper for use in our mocha tests, we'll need to set up a mocha.opts file that specifies a few configuration options. 为了利用此jsdom帮助程序在我们的Mocha测试中使用,我们需要设置一个mocha.opts文件,该文件指定一些配置选项。 We'll add a compiler that will tell Babel to pre-process the tests, and we'll require the jsdom helper so React has a DOM to use to render components. 我们将添加一个编译器,该编译器将告诉Babel预处理测试,并且require jsdom帮助器,以便React可以使用DOM来呈现组件。

mocha.opts: mocha.opts:

--compilers js:babel-register
--recursive
--reporter spec
--ui bdd
--require ./test/util/jsdom.js

Finally, we can start testing React components. 最后,我们可以开始测试React组件了。 As an example, here is a simple component that we can test. 例如,这是一个我们可以测试的简单组件。

test-component.js: 测试component.js:

import React from 'react';

export default class TestComponent extends React.Component {
    render() {
        return (
            <div className="test-component">Here is a test component</div>
        );
    }
}

And here is a test suite that will test this component's markup. 这是一个测试套件,将测试该组件的标记。

test-component.spec.js: 测试component.spec.js:

import TestComponent from '../../src/test-component';
import {expect} from 'chai';

import React from 'react';
import ReactDOM from 'react-dom';
import ReactTestUtils from '../../node_modules/react/lib/ReactTestUtils';

describe('Test Component', () => {
    let renderedNode;

    function renderComponent() {
        const componentElement = React.createElement(TestComponent),
            renderedElement = ReactTestUtils.renderIntoDocument(componentElement);

        renderedNode = ReactDOM.findDOMNode(renderedElement);
    }

    beforeEach(() => {
        renderComponent();
    });

    it('should exist with the correct markup', () => {
        expect(renderedNode.tagName).to.equal('DIV');
        expect(renderedNode.className).to.equal('test-component');
        expect(renderedNode.textContent).to.equal('Here is a test component');
    });
});

At this point, the command npm run test should result in a single passing test. 此时,命令npm run test应该导致一个通过测试。

And that's it! 就是这样! If you're looking for more advanced testing techniques, you can completely avoid the need for a jsdom helper and use shallow rendering for your tests. 如果您正在寻找更高级的测试技术,则可以完全避免使用jsdom帮助器,并使用浅层呈现进行测试。 I highly recommend Enzyme if you want to take this approach. 如果您想采用这种方法,我强烈推荐

Let me know if you have any questions! 如果您有任何疑问,请告诉我!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM