unit-testing - 类型错误 : Cannot read property 'contextTypes' of undefined

标签 unit-testing reactjs jestjs enzyme

我正在尝试使用 Jest 测试 React 应用程序。我使用 Enzyme 的浅层在 App-test-js 中渲染我的 App.js 组件,但收到此错误:TypeError: Cannot read property 'contextTypes'未定义的

这是我的App.js:

/* global google */
import React, { Component } from 'react';
import Geosuggest from 'react-geosuggest';
import { getAirQuality } from './Client'
import DataTable from './DataTable'
import Errors from 'react-errors'


class App extends Component {

  .
  .
  .

  render() {
    return (
      <div className="App">
        <form onSubmit={this.searchAirQuality.bind(this)}>
          <Geosuggest
            placeholder="Type a location and press SEARCH button!"
            onSuggestSelect={this.onSuggestSelect.bind(this)}
            initialValue={this.state.place}
            location={new google.maps.LatLng(53.558572, 9.9278215)}
            radius="20"/>
          <button className="my-button" type="submit" disabled={!this.state.place}>Button</button>
        </form>
        <DataTable items={this.state.items} />
        <Errors
          errors={this.state.errors}
          onErrorClose={this.handleErrorClose}
        />
      </div>
    )
  }
}

export default App;

这是我的App-test.js:

import React from 'react'
import { shallow } from  'enzyme'
import App from '../components/App.js'

describe( '<App />', () => {
  it('Button disable when input is empty', () => {
    const App = shallow(<App />);

    expect(App.find('.my-button').hasClass('disabled')).to.equal(true);

  });

});

这是我运行npm test时出现的错误:

Terminal screenshot

这是我第一次 Jest 进行测试,请问有人可以帮助我解决这个错误吗?

最佳答案

您导入不存在的内容时,这将是相同的错误TypeError:无法读取未定义的属性“contextTypes”

这是一个例子:
AccountFormComponent.jsx(不正确的类名):

export class FoeFormComponent extends React.Component { .... }

AccountFormComponent.test.jsx:

import { shallow } from 'enzyme'
import { expect, assert } from 'chai'
import { AccountFormComponent } from '../../src/components/AccountFormComponent';

describe('', function () {
  it('', function () {
    const enzymeWrapper = shallow(<AccountFormComponent {...props} />);
  });
});

只需将以下内容添加到您的测试文件中即可确保该组件存在:

it('should exists', function () {
    assert.isDefined(AccountFormComponent);
});

打印AssertionError:预期未定义不等于未定义而不是

关于unit-testing - 类型错误 : Cannot read property 'contextTypes' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39796060/

相关文章:

javascript - 在 native react 中获取类型错误 undefined object ?

javascript - bundle.js 显示 HTML 代码而不是 javascript

javascript - 引用错误 : Cannot access 'mockMethod1' before initialization

node.js - 使用 Jest 模拟模块无法正常工作

c# - xUnit测试asp net core Mapper未初始化

django - 我应该在 Django 中测试我的通用 DetailView

reactjs - 导入使用 React-Router-Dom 的自定义模块组件时出现问题

javascript - 将 web3.js 与 Jest 一起使用时出错

javascript - 如何在 Chai 中模拟或 stub 'instanceof' |诗农 |摩卡

node.js - nodejs/mocha/nock - 模拟整个 html 响应