首页 > 解决方案 > Karma test in React app , failing with "TypeError: (0 , _expect2.default)(...).toExist is not a function"

问题描述

I am new to React, and facing this failing test issue in my app (FilterItems component). Would greatly apprecitate any guidance or help.

Here's my simple FilterItems component.

import React, { Component } from 'react';

class FilterItems extends React.Component {
  render () {
    return (
      <div className="filter-items">
        {this.props.data.map(item => (<div className="filter-item">{item.name}</div>))}
      </div>

    )
  }
}

export default FilterItems;

And here's the test I am running on it, which fails - with the error " TypeError: (0 , _expect2.default)(...).toExist is not a function at Context. (src/tests/FilterItems.test.js:57453:40)"

My FilterItems.test.js file below

import React from 'react';
import expect from 'expect';
import FilterItems from '../components/FilterItems';
import ReactTestUtils from 'react-dom/test-utils'; // ES6


describe('FilterItems', () => {
  it('should exist', () => {
    expect(FilterItems).toBeTruthy();
  });
});          


describe('FilterItems', function () {
  it('loads without problems', function () {
    var filterItems = ReactTestUtils.renderIntoDocument(<FilterItems
      data={ [1, 2, 3] }
      />);

  expect(filterItems).toExist();
  });
});

Just in case it helps, below is the karma.conf.js file

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

module.exports = function (config) {
  config.set({
    browsers: ['Chrome'],
    singleRun: true,
    frameworks: ['mocha'],
    files: [
      'src/tests/**/*.test.js'
    ],
    preprocessors: {
      'src/tests/**/*.test.js': ['webpack', 'sourcemap']
  },
  reporters: ['mocha'],
  client: {
    mocha: {
      timeout: '5000'
    }
  },
  webpack: webpackConfig,
  webpackServer: {
    noInfo: true
  }
});
};

标签: reactjsunit-testingkarma-mochareact-test-renderer

解决方案


由于某种原因,从期望函数返回的对象中不存在此函数,并且文档是错误的。我建议使用 toBeTruthy 别名。


推荐阅读