如何解决:TypeError:ReactWrapper :: state(“ <state>”)要求`state`不能为null或未定义

时间:2019-05-24 04:08:33

标签: react-router tdd enzyme assertion react-wrapper

我正在用酶测试Create-React-App中的状态。我如何通过此考试?

在测试中呈现我的App组件时,它包装在

<BrowserRouter>

(尝试将其挂载,否则会产生

 Invariant failed: You should not use <Route> outside a <Router>

测试错误)。

包装纸浅

 TypeError: Cannot read property 'state' of null

使用

进行安装和包裹
<BrowserRouter>.

我尝试过this

结果:问题未解决

this

结果:问题未解决

this

结果:卸载react-test-renderer没什么作用

this

结果:我检查了组件中的状态并定义了状态。 console.log(wrapper.instance()。state)产生相同的错误:'null'

App.js:

class App extends Component {
  //#region Constructor
  constructor(props) {
    super(props);
    this.state = {
    //... other correctly formatted state variables
      specificRankingOptionBtns: false
    }

app.test.js:

import React from 'react'
import { BrowserRouter } from 'react-router-dom'
import App  from '../../App'
import renderer from 'react-test-renderer'
import { shallow, mount } from 'enzyme';

describe('App', () => {
fit('renders App.js state correctly', () => {
  const wrapper = mount(<BrowserRouter><App /></BrowserRouter>);
  //console.log(wrapper.instance().state);
  //const wrapper = shallow(<App />);
  //const wrapper = mount(<App />);
  console.log(wrapper.instance().state);
  //const wrapper = mount(shallow(<BrowserRouter><App /> 
  //</BrowserRouter>).get(0));
  expect(wrapper.state('specificRankingOptionBtns')).toEqual(false);
});
}

期望:通过测试

实际:“ TypeError:ReactWrapper :: state(“ specificRankingOptionBtns”)要求state不能为nullundefined

1 个答案:

答案 0 :(得分:1)

我有同样的问题。这对我有用。

从“ react-router-dom”导入{MemoryRouter as Router};

it('should find MaskedTextInput in LoginPage', () => {
    const mountWithRouter = node => mount(<Router>{node}</Router>);
    const wrapper = mountWithRouter(<LoginPage {...mockedProps} />);
    const maskedInput = wrapper.find('MaskedTextInput');

    const componentInstance = wrapper
        .childAt(0)
        .childAt(0) 
        .instance(); // could also be instance

    const mountedState = componentInstance.state.passwordInputType;
    expect(mountedState).toEqual('password');
});