我正在尝试使用 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
时出现的错误:
这是我第一次 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/