首页 > 解决方案 > 在使用反应测试库中的反应测试库测试我的包含 i18next 库的组件时,将错误显示为“无法读取 null 的属性‘等待’”

问题描述

这是我正在尝试测试的文件

所以这是我的 about 文件,其中包含 i18next 库,因为我收到错误为“无法读取 null 的属性等待

import React, { Component } from 'react';
import LoadingImg from '../../assets/images/loader.gif'
import {getChapterData,fetchChapterData,htmlDecode} from '../helpers/common'
import { Trans, withNamespaces } from 'react-i18next';
class AboutReportChapter extends Component {
   constructor(props){
       super(props)
       this.state={
           isDataLoaded:false
       }
   }
   
   
   render() {
       return (
           <div className="drChapterContainer aboutChapterReport" id="pills-AboutReportChapter">
               {this.state.isDataLoaded?
                   <div className="aboutReport">
                       {this.state.chapterDescription ?
                           <div className="aboutReportHeader flexContainer">
                                   <div className="hideShowAll show unselectable" id="about_HS"><Trans>HIDE_ALL</Trans></div>
                           </div>
                           :null
                       }
                       
                   </div>
               :
                   <div className="loading" key="loading_key">
                       <img src={LoadingImg} alt ="Loading"/>
                   </div>
               }
           </div>
       )
   }
   componentDidMount= async()=> { 
       let result = await fetchChapterData('AboutReportChapter')
       this.setState({...result});
   }
}

export default withNamespaces() (AboutReportChapter);

这是我的测试文件

这是我正在使用反应测试库 jest 测试的测试文件,我在渲染组件时得到空值

import React from 'react'
import About from '../about'
import { render,unmountComponentAtNode} from "react-dom";
import { screen,getByText,getByTestId,queryByText } from '@testing-library/dom'
import {fetchChapterData,htmlDecode} from '../../helpers/common'
import { act } from "react-dom/test-utils";



jest.mock('../../helpers/common', () => ({
  fetchChapterData:jest.fn(),
  htmlDecode:jest.fn()
}))

let container = null;
beforeEach(() => {
  // setup a DOM element as a render target
  container = document.createElement("div");
  document.body.appendChild(container);
});

afterEach(() => {
  // cleanup on exiting
  unmountComponentAtNode(container);
  container.remove();
  container = null;
});

describe("Introduction component testing",() => {

    const fakeData=require('../_Mock Data_/about.json');
    

    fetchChapterData.mockResolvedValue({...fakeData})
 
  
    it("check if about component is rendered or not", async () => {

      
        await act(async () => {
            render(<About t={key => key} />, container);
        });

        //Assertions

        expect(container.getElementsByClassName('aboutReport').length).toBe(1);
        expect(container.getElementsByClassName('loading').length).toBe(0);
        

    });

})

标签: javascriptreactjstestingjestjs

解决方案


推荐阅读