3

我的期望是,当我使用 Enzyme 的mount功能时,我应该不仅可以查询顶级元素中的节点,还可以查询子组件中呈现的节点/元素。

以下是这件事中展示的测试:

import React from 'react';
import chai from 'chai'
import chaiEnzyme from 'chai-enzyme'
chai.use(chaiEnzyme());
const expect = chai.expect;

import {
  shallow,
  mount
} from 'enzyme';

class Child extends React.Component {
  render() {
    return <div id='child'>
      CHILD
      <button onClick={() => console.log('hit me')}>HIT ME</button>
     </div>
  }
}

class Parent extends React.Component {

  render() {
    return <div id='root'>
      <Child aprop={1}/>
    </div>
  }
}


describe('example', function() {
  describe('mounted', function() {
    it('should find the button', function() {
      const wrapper = mount(<Parent/>);
      expect(wrapper.find('button').length).to.equal(1);
    });

    it('should find Child component', function() {
      const wrapper = mount(<Parent/>);
      console.log(wrapper.debug());
      expect(wrapper.find(Child).length).to.equal(1);
    });
  });
  describe('shallow', function() {
    it('should not find the button', function() {
      const wrapper = shallow(<Parent/>);
      expect(wrapper.find('button').length).to.equal(0);
    });

    it('should find Child component', function() {
      const wrapper = shallow(<Parent/>);
      expect(wrapper.find(Child).length).to.equal(1);
    });
  });
});

输出是:

example
    mounted
      ✗ should find the button
    expected 0 to equal 1
    AssertionError@webpack:///~/assertion-error/index.js?6193**:74:0 <- test/components/mount.spec.js:373:25
    assert@webpack:///~/chai/lib/chai/assertion.js?fee1**:107:0 <- test/components/mount.spec.js:4705:32
    assertEqual@webpack:///~/chai/lib/chai/core/assertions.js?b343**:487:0 <- test/components/mount.spec.js:5222:19
    webpack:///~/chai/lib/chai/utils/addMethod.js?ca90**:41:0 <- test/components/mount.spec.js:4292:31
    webpack:///test/components/mount.spec.js:35:53 <- test/components/mount.spec.js:153:54

LOG LOG: '<Parent />'
      ✗ should find Child component
    expected 0 to equal 1
    AssertionError@webpack:///~/assertion-error/index.js?6193**:74:0 <- test/components/mount.spec.js:373:25
    assert@webpack:///~/chai/lib/chai/assertion.js?fee1**:107:0 <- test/components/mount.spec.js:4705:32
    assertEqual@webpack:///~/chai/lib/chai/core/assertions.js?b343**:487:0 <- test/components/mount.spec.js:5222:19
    webpack:///~/chai/lib/chai/utils/addMethod.js?ca90**:41:0 <- test/components/mount.spec.js:4292:31
    webpack:///test/components/mount.spec.js:41:50 <- test/components/mount.spec.js:159:51

    shallow
      ✓ should not find the button
      ✓ should find Child component

要么 mount 没有按预期工作,要么我的理解不正确。

如果有帮助,这是我的 Karma/Webpack 文件:

const webpack = require('webpack');
var argv = require('yargs').argv;
var path = require('path');
let srcPath = path.join(__dirname, '/../src/');

const webpackConfig = {
    devtool: 'inline-source-map',
    resolve: {
        // allow us to import components in tests like:
        // import Example from 'components/Example';
        root: path.resolve(__dirname, './src'),

        // allow us to avoid including extension name
        extensions: ['', '.js', '.jsx', '.css', '.scss', '.json'],

        // required for enzyme to work properly
        alias: {
            'sinon': 'sinon/pkg/sinon',
        }
    },
    module: {
        // don't run babel-loader through the sinon module
        noParse: [
            /node_modules\/sinon\//
        ],
        isparta: {
                embedSource: true,
                noAutoWrap: true,
                // these babel options will be passed only to isparta and not to babel-loader
                babel: {
                        presets: ['es2015', 'stage-0', 'react']
                }
        },
        // run babel loader for our tests
        loaders: [
            {
        test: /\.(js|jsx)$/,
        loader: 'babel',
        exclude: path.resolve(__dirname, 'node_modules'),
        query: {
            plugins: ['transform-decorators-legacy'],
          presets: ['es2015', 'airbnb', 'stage-1', 'react']
        }
      },
            {
                test: /\.json$/, loader: 'json'
            },
            {
                test: /\.scss$/,
                exclude: /[\/\\](node_modules|bower_components|public)[\/\\]/,
                loaders: [
                    'style?sourceMap',
                    'css?modules&importLoaders=1&localIdentName=[local]',
                    'postcss',
                    'sass'
                ]
            },
            {
                test: /\.css$/,
                exclude: /[\/\\](node_modules|bower_components|public)[\/\\]/,
                loaders: [
                    'style?sourceMap',
                    'css?modules&importLoaders=1&localIdentName=[local]'
                ]
            }
        ],
        preLoaders: [ { //delays coverage til after tests are run, fixing transpiled source coverage error
            test: /\.(jsx|js)$/,
            include: path.resolve('src/'),
            loader: 'isparta',
        } ]
    },
    plugins: [
        new webpack.IgnorePlugin(/node-fetch/)
    ],
    // required for enzyme to work properly
    externals: {
        'jsdom': 'window',
        'react/lib/ExecutionEnvironment': true,
        'react/lib/ReactContext': 'window',
        'react/addons': true
    },
};

module.exports = function(config) {
    config.set({
        browsers: ['PhantomJS'],
        singleRun: !argv.watch,
        frameworks: ['mocha', 'chai'],
        reporters: ['spec', 'coverage'],

        // include some polyfills for babel and phantomjs
        files: [
            'node_modules/whatwg-fetch/fetch.js',
            'node_modules/babel-polyfill/dist/polyfill.js',
            './node_modules/phantomjs-polyfill/bind-polyfill.js',
            'test/**/*.js'
        ],
        preprocessors: {
      // add webpack as preprocessor
      'src/**/*.js': ['webpack', 'sourcemap'],
      'test/**/*.js': ['webpack', 'sourcemap']
    },
        // A lot of people will reuse the same webpack config that they use
        // in development for karma but remove any production plugins like UglifyJS etc.
        // I chose to just re-write the config so readers can see what it needs to have
        webpack: webpackConfig,
        webpackMiddleware: {
            noInfo: true
        },
        coverageReporter: {
            dir: 'coverage/',
            reporters: [
                { type: 'html' },
                { type: 'text' }
            ]
        },
        // tell karma all the plugins we're going to be using to prevent warnings
        plugins: [
            'karma-mocha',
            'karma-chai',
            'karma-webpack',
            'karma-phantomjs-launcher',
            'karma-spec-reporter',
            'karma-sourcemap-loader',
            'karma-coverage'
        ]
    });
};
4

0 回答 0