Reactjs 如何测试react方法的输出是否正确?

Reactjs 如何测试react方法的输出是否正确?,reactjs,jestjs,babel-jest,Reactjs,Jestjs,Babel Jest,我在试图理解如何使用Jest测试react文件中方法的输出时遇到问题。我对这种风格的web开发完全陌生,因此非常感谢您的帮助 我有这样一个js文件: import * as React from 'react'; import 'es6-promise'; import 'isomorphic-fetch'; export default class FetchData extends React.Component { constructor() { super();

我在试图理解如何使用Jest测试react文件中方法的输出时遇到问题。我对这种风格的web开发完全陌生,因此非常感谢您的帮助

我有这样一个js文件:

import * as React from 'react';
import 'es6-promise';
import 'isomorphic-fetch';

export default class FetchData extends React.Component {
    constructor() {
        super();
        this.state = { documents: [], loading: true };
        fetch('api/SampleData/GetDocuments')
            .then(response => response.json())
            .then(data => {
                this.setState({ documents: data, loading: false });
            });
    }

    render() {
        let contents = this.state.loading ? <p><em>Loading...</em></p>
            : FetchData.renderdocumentsTable(this.state.documents);

        return <div>
            <button onClick={() => { this.refreshData() }}>Refresh</button>
            <p>This component demonstrates bad document data from the server.</p>
            {contents}
        </div>;
    }

    refreshData() {
        fetch('api/SampleData/GetDocuments')
            .then(response => response.json())
            .then(data => {
                this.setState({ documents: data, loading: false });
            });
    }

    static renderdocumentsTable(documents) {
        return <table className='table'>
            <thead>
                <tr>
                    <th>Filename</th>
                    <th>CurrentSite</th>
                    <th>CorrectSite</th>
                </tr>
            </thead>
            <tbody>
                {documents.map(document =>
                    <tr className="document-row" key={document.documentId}>
                        <td>{document.filename}</td>
                        <td>{document.currentSite}</td>
                        <td>{document.correctSite}</td>
                    </tr>
                )}
            </tbody>
        </table>;
    }
}
import*as React from'React';
进口‘es6承诺’;
导入“同构提取”;
导出默认类FetchData扩展React.Component{
构造函数(){
超级();
this.state={documents:[],load:true};
获取('api/SampleData/GetDocuments')
.then(response=>response.json())
。然后(数据=>{
this.setState({documents:data,load:false});
});
}
render(){
让内容=this.state.loading?加载

:FetchData.renderdocumentsTable(this.state.documents); 返回 {this.refreshData()}}>Refresh 此组件演示来自服务器的错误文档数据

{contents} ; } 刷新数据(){ 获取('api/SampleData/GetDocuments') .then(response=>response.json()) 。然后(数据=>{ this.setState({documents:data,load:false}); }); } 静态渲染文档稳定(文档){ 返回 文件名 当前站点 正确的 {documents.map(document=> {document.filename} {document.currentSite} {document.correctSite} )} ; } }
我基本上希望能够测试一个表是否返回了正确的列数,但是我不知道如何使用Jest来实现这一点

谢谢,
Alex

我遵循下一种方法:

  • 被测试组件显式调用
  • 正在使用初始化组件
  • 尝试不同的修改
  • 使用检查组件
  • 在“尝试不同的修改”下,我的意思是使用不同的初始
    道具创建组件,或者与组件的内部元素
    道具进行交互

    test('closes list on button clicked', () => {
        let wrapper = shallow(<MyComponent prop1={'a'} prop2={'b'} />);
        wrapper.find('button').at(0).simulate('click');
        expect(wrapper).toMatchSnapshot();
    });
    

    我尝试了很多像你们说的东西,但我还是做得不对。在线教程中似乎没有一个例子看起来像我的react课程。例如,从“React”导入React;从“./FetchData”导入FetchData;从“反应测试渲染器”导入渲染器;它('正确呈现',()=>{const tree=renderer.create().toJSON();expect(tree.toMatchSnapshot();});只是不起作用。你能举个例子,用我原始问题附带的类吗?:)太神了非常感谢你!注:我还需要添加酶,并设置为浅:)
    describe("<FetchData />", () => {
      let wrapper;
      global.fetch = jest.fn();
    
      beforeEach(() => {
        fetch.mockClear();
      });
    
      function makeFetchReturning(documents) {
        fetch.mockImplementation(() => Promise.resolve({ json: () => documents }));
      }
    
      function initComponent() {
        // if we run this in beforeEach we would not able to mock different return value for fetch() mock
        wrapper = shallow(<FetchData />); 
      }
    
      test("calls appropriate API endpoint", () => {
        makeFetchReturning([]);
        initComponent();
        expect(fetch).toHaveBeenCalledWith("api/SampleData/GetDocuments");
      });
    
      test("displays loading placeholder until data is fetched", () => {
        // promise that is never resolved
        fetch.mockImplementation(() => new Promise(() => {})); 
        initComponent();
        expect(wrapper).toMatchSnapshot();
      });
    
      test("looks well when empty data returned", () => {
        makeFetchReturning([]);
        initComponent();
        expect(wrapper).toMatchSnapshot();
      });
    
      test("reloads documents and displays them", () => {
        makeFetchReturning([]);
        initComponent();
        // no matter what values we include in mock but it should be something non-empty
        makeFetchReturning([{fileName: '_', currentSite: '1', correctSite: '2'}]);
        wrapper.find('button').at(0).simulate('click');
        expect(fetch).toHaveBeenCalledTimes(2);
        expect(wrapper).toMatchSnapshot();
      })
    
    });