使用Jest测试React组件中的功能

时间:2020-08-07 23:45:45

标签: reactjs mocking jestjs enzyme

我对使用react组件进行单元测试非常陌生。我有一个react组件,可以在单击时从props复制给定的id。这就是从一个单独的文件中调用一个函数以执行copyToClipboard函数,然后将react组件的状态设置为“已复制”。我正在尝试测试这些功能,并可能将状态值更改为“已复制”。每当我尝试模拟onclick函数时,都会出现错误消息“无法读取未定义的属性'writeText'”。这是因为onClick函数为此过程调用了一个单独的函数,是否可以模拟其他函数并将其传递给onClick()函数或其他解决方案?或任何指示我应该如何前进?

App.js

  let filterArray = [
  {
    branchCode: "AV1",
    summaryCount: 10
  },
  {
    branchCode: "AV2",
    summaryCount: 5
  },
  {
    branchCode: "BR1",
    summaryCount: 4
  }]

  loadTable() {
    this.service.getSomeDataFromAPI().pipe(
      map(
        items => items.filter( item => {
          if (filterArray.find(filterItem => filterItem.branchCode == item.branchCode)) {
            return true
          } else {
            return false
          }
        })   
      )
    ).subscribe(response => {  ...  });
  }

测试文件

import React from "react";
import "./styles.css";
import {copyToClipboard} from './CopyFile'
export default function App({id}) {
  const [copyStatus, setCopyStatus] = useState('')

  const copyLineItemId=(id)=>{
    copyToClipboard(id)
    setCopyStatus('Copied')
    setTimeout(function () {
      setCopyStatus('')
    }, 2000)
  }

  return (
    <div>
      <i id="copy" className="fa fa-copy" onClick={() =>copyLineItemId({id})}></i>
      <p id="status">{copyStatus}</p>
  </div>
  );
}

复制函数CopyFile.js

import React from 'react'
import { mount } from 'enzyme'
import { MockedProvider } from '@apollo/react-testing'

function getComponent(props) {
  const { componentProps } = props
  return (
    <MockedProvider>
      <CopyComponent {...componentProps} />
    </MockedProvider>
  )
}


test('copy function', () => {
    const componentProps = {
      id:123
    }

    const wrapper = mount(getComponent({ componentProps }))

    wrapper.find("#copy").simulate('click')

    expect(wrapper.find("#status")).toEqual("Copied")
  })

1 个答案:

答案 0 :(得分:0)

在JSdom中,apx =int(input("TYPE 1 TO KNOW MORE ABOUT APX: \n")) if apx == 1: print(" I was Created By Hani Jaafar He is Only 13 years Old But He is a member of a company Known as D.H PRODUCTION It Was Founded By \n") print("DHAVEEN AHAMMED AND HANI JAAFAR I LIKE BOTH OF THEM") else: print("Try again: ") 未定义,因此您必须自己定义它,如下所示:

navigator.clipboard.writeText()