Skip to content

React UnitTest

ythy edited this page Dec 28, 2017 · 1 revision
  1. Test Runner: KarmaJS
  2. Testing Framework : jasmine
  3. Assertion Library : jasmine
  4. react dom test : react-dom/test-utils
  5. react shallow test : react-test-renderer/shallow

Test Runner

The test runner is responsible for actually running the test code that you’ve written. In the case of KarmaJS, you’ll write a configuration file that spins up a web server to execute your test code in different browsers and then displays the test results for you. What’s important to note is that the test runner is useless unless its configured to use a testing framework, assertion library, and other plugin libraries

Testing Framework

The testing framework is responsible for structuring your test code. It provides methods that are concerned with structuring your test code so that you’ll have different code blocks for testing each of your source files and code blocks for testing a different functionalities in a source file.

assertion library

The assertion library is responsible for checking / asserting whether the values you expect are actually the values you get. The set of methods bundled with an assertion library typically compare 2 values and determine whether they are equal. Typically, your test code will use methods from your testing framework to structure the tests into code blocks, and then use methods from your assertion library within each code block to assert whether your expectation is correct.

配置案例

安装清单:

"@types/jasmine": "^2.8.2",
"@types/react-test-renderer": "^16.0.0",
"jasmine-core": "^2.8.0",
"karma": "^2.0.0",
"karma-chrome-launcher": "^2.2.0",
"karma-jasmine": "^1.1.1",
"karma-webpack": "^2.0.9",
"react-test-renderer": "^16.2.0",

karma 配置文件:

var webpackConfig = require('./webpack.config');

module.exports = function(config) {
    config.set({

         // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        frameworks: ["jasmine"],

        // list of files / patterns to load in the browser
        files: [
            '_test_/**/*.ts'
        ],

        // list of files to exclude
        exclude: [
        ],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            'src/**/*.{ts,tsx}': [ 'webpack' ], // Using karma-webpack npm module
            '_test_/**/*.{ts,tsx}': [ 'webpack' ]
        },
        
        webpack: {
          module: webpackConfig.module,
          resolve: webpackConfig.resolve,
          plugins: webpackConfig.plugins
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ["dots"],

        browsers: ["Chrome"],

         // web server port
        port: 9176,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

    });
};

测试案例:

import React from 'react';
import ShallowRenderer from 'react-test-renderer/shallow';
import TestUtils, { SyntheticEventData } from 'react-dom/test-utils';
import ReactDOM from 'react-dom';

const renderer = ShallowRenderer.createRenderer();

describe("UInput", () => {

  let input: React.ReactElement<InputProps>;

  beforeEach(() => {
    //注意这里要把控件转换为ReactElement 不能直接写<UInput />
    input = React.createElement(UInput, {
      maxAscii: 10,
      restrict: '0-9',
      value: 1,
      onCurrentChange: (v:string)=>{
        console.log('onCurrentChange : ' + v);
      }
    });  
  });

  it("should render correctly", () => {
    renderer.render(input);
    const result:React.ReactElement<InputProps> = renderer.getRenderOutput();
    expect(result.type).toEqual("input");
  });

  it("should have correct prop values", () => {
    const instance = TestUtils.renderIntoDocument(input) as React.Component;
    const domNode = ReactDOM.findDOMNode(instance);

    expect(domNode).toBeDefined();
    expect(domNode.getAttribute('value')).toContain('1');

    instance.setState({ inputValue: '9' });
    expect(domNode.getAttribute('value')).toContain('9');
  });
});

Clone this wiki locally