programing

TypeError: 정의되지 않은 'contextTypes' 속성을 읽을 수 없습니다.

mbctv 2023. 3. 17. 21:55
반응형

TypeError: 정의되지 않은 'contextTypes' 속성을 읽을 수 없습니다.

Jest와 리액트 앱을 테스트하려고 합니다.난 효소의 얕은 곳을 이용해서App.js구성 요소App-test-js이 에러가 표시됩니다.TypeError: Cannot read property 'contextTypes' of undefined

이건 내 거야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:

단말 스크린샷

장난으로 테스트하는 것은 처음입니다만, 혹시 이 에러에 대해 가르쳐 주실 수 있겠습니까?

이것은 같은 에러가 됩니다.TypeError: Cannot read property 'contextTypes' of undefined존재하지 않는 것을 Import 하는 경우.

다음은 예를 제시하겠습니다.
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: expected undefined to not equal undefined대신

여기서 문제는 얕은 호출 결과로 앱 구성요소를 재정의하고 있다는 것입니다.

//    Redefining
//    ↓
const App = shallow(<App />);

해결책은 다른 이름을 사용하는 것입니다.

//    Use a different name
//    ↓
const app = shallow(<App />);

이 경우 디폴트 내보내기가1개밖에 없는 모듈을 Import 했을 때 오류가 발생했는데, 저는 싱글 Import를 사용하고 있었습니다.

그래서 다음 대신:

import { Foo } from './Foo'

용도:

import Foo from './Foo'

여기서 Foo는 기본 내보내기를 사용합니다.

class Foo extends Component {
  render() {
   return (<div>foo</div>)
  }
}
export default Foo;

@Ser가 언급했듯이 Import의 문제가 될 수 있습니다.eslint 규칙을 사용하는 경우 Import 실패 시 힌트를 얻을 수 있습니다.

"import/no-unresolved": 1,

jsx 파일에서 컴포넌트를 Import하려고 할 때 오류가 발생하였습니다.

import {Header} from './Header';

이것으로 해결되었다

import {Header} from './Header.jsx';

또, Web 팩을 사용하고 있기 때문에, 「.jsx」를 resolve.extensions 옵션에 추가해 둘 필요가 있었습니다.이렇게 하면 가져올 때 확장을 무시할 수 있습니다.

이 경우 이름 있는 구성 요소 구문을 사용하여 기본 구성 요소를 가져오고 있었습니다.

예를 들어 다음과 같습니다.

import {TestComponent} from "../../components/TestComponent";

대신

import TestComponent from "../../components/TestComponent";

올바른 구문을 사용하도록 가져오기를 업데이트하면 문제가 수정되었습니다.바보같은 놈이지.

언급URL : https://stackoverflow.com/questions/39796060/typeerror-cannot-read-property-contexttypes-of-undefined

반응형