【问题标题】:How to write test case for a component which is calling a method using jest如何为使用 jest 调用方法的组件编写测试用例
【发布时间】:2021-06-20 00:35:07
【问题描述】:

我是 Jest 和 Enzyme 的新手,遇到了一个问题。有人可以帮忙吗? 这是我的 jsx 文件(myTemplate.jsx):

export default (props) => {
  const oneSection = () => {
        return <div>Hello</div>
    };

  return (
    props.hasData ? { <div>Hey</div> } : { <div><oneSection/></div> }
   )
}

这是我的测试文件:

import React from "react";
import { shallow } from "enzyme";
import myTemplate from '../myTemplate';

 describe("template component", () => {
 const props= {
        hasData: false,
 }
 let myComponent = null;
    beforeAll(() => {
        myComponent = shallow(<myTemplate {...props}/>);
    })
    test("should render with initial state properly", () => {
        expect(myComponent).toMatchSnapshot();
    })
  })

现在这个测试用例运行成功了。使用具有 oneSection 的 div 创建快照,但 oneSection 并没有被其中的实际 html 替换。基本上这些行没有被覆盖:

 const oneSection = () => {
            return <div>Hello</div>
        };

如何使用 Jest 和酶覆盖这段代码?

【问题讨论】:

    标签: javascript reactjs jestjs enzyme


    【解决方案1】:
    import React from 'react'
    import { cleanup, render } from '@testing-library/react'
    
    describe('DMReports', () => {
      afterEach(cleanup)
      test('DMReports: hasData true', () => {
        const { container } = render(
          <DMReports hasData={true}/>,
        )
        expect(container).toMatchSnapshot()
      })
      test('DMReports: hasData false', () => {
        const { container, getByText } = render(
          <DMReports hasData={false}/>,
        )
        expect(container).toMatchSnapshot()
        expect(getByText('Hello')).toBeTruthy()
      })
    })
    

    【讨论】:

    • 不使用@testing-library/react 有其他方法吗?
    • 删除beforeAll 并使用不同的props初始化myComponent = shallow(&lt;myTemplate {...props}/&gt;)
    • 这样做是再次使用 创建快照,但不会将 oneSection 替换为
      Hello
    猜你喜欢
    • 1970-01-01
    • 2019-05-26
    • 1970-01-01
    • 2019-04-24
    • 2021-09-05
    • 2023-03-08
    • 2018-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多