簡體   English   中英

如何使用道具測試反應組件?

[英]How to test a react component with props?

我需要使用 props 測試一個 react 組件安裝正常,並正確呈現其內容,例如 paras 和 divs。 我的代碼可以在下面或這個沙箱中找到

我嘗試使用默認道具對其進行測試,但這不起作用。

import React from 'react';
import test from 'tape';
import {mount} from 'enzyme';


test('testing', t => {


  t.doesNotThrow(() => {
    wrapper = mount(<App2 txt={ok}/>);
  }, 'Should mount');


  t.end();
});

這是我的道具組件。

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import App from './index'

export default class App2 extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React'
    };
  }

  render() {
    const {txt}=this.props
    return (
      <div>
        <p>hi {txt}</p> 
     </div>
    );
  }
}

以及提供道具的外部組件。

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import App2 from './app2'

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React'
    };
  }

  render() {
    return (
      <div>
        <Hello name={this.state.name} />
        <p>
          Start editing to see some magic happen :)
        </p>
        <App2 txt={this.state.name}/>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

所以你會做一些事情,比如自己提供屬性並確保它與它們一起呈現:

test('test your component', () => {
  const wrapper = mount(<App2 txt={'michaelangelo'} />);

  expect(wrapper.find('p').text()).toEqual('hi michaelangelo');
});

你不應該擔心像這樣測試 和 html 元素,而是你傳遞的道具並且它們在正確的地方呈現,即在 p 標簽中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM