开玩笑:fireEvent.submit(...)不是一个函数

时间:2020-07-25 18:01:25

标签: reactjs unit-testing testing jestjs react-testing-library

im trynna测试我的代码,但给出错误“ TypeError:_react2.fireEvent.submit(...)不是函数” ,我不知道如何解决它,此错误当我在第二个测试中放置**"({ getByText, getByTestId, getByLabelText } = render(<TechList />)) "**时出现。

即使重新渲染,我也需要测试文本“ Node.js”是否仍保留在组件中。

我的测试代码如下:

    import '@testing-library/jest-dom/extend-expect'
import React from 'react' 
import { render, fireEvent } from '@testing-library/react'

import TechList from '../components/Techlist'

 describe('TechList component', () => {
 
   it('should be able to add new Tech', () => {  
      const { getByText, getByTestId, getByLabelText } = render(<TechList />)

      fireEvent.change(getByLabelText('Tech'), { target: { value: 'Node.js' }})
      fireEvent.submit(getByTestId('tech-form')) 
    
      expect(getByTestId('tech-list')).toContainElement(getByText('Node.js'))
      expect(getByLabelText('Tech')).toHaveValue('')
   })
 
   it('should store techs in storage', () => {
     let { getByText, getByTestId, getByLabelText} = render(<TechList />)

     fireEvent.change(getByLabelText('Tech'), { target: { value: 'Node.js' }})
     fireEvent.submit(getByTestId('tech-form')) 

    ({ getByText, getByTestId, getByLabelText } = render(<TechList />)) 

     expect(getByTestId('tech-list')).toContainElement(getByText('Node.js'))
   })
 
 })

和组件:

    import React, { useState } from 'react'; 

function Component() {
  const [techs, setTechs] = useState([])
  const [newTech, setNewTech] = useState('')
  
  function handleAddTech() {
    setTechs([...techs, 'Node.js'])
    setNewTech('')
  }

  return (
    <form data-testid="tech-form" onSubmit={handleAddTech} >      
     
      <ul data-testid="tech-list">
      {techs.map(tech => <li key={tech}>{tech}</li>)}
      </ul>
      <label htmlFor="tech">Tech</label>
      <input id="tech" type="text" value={newTech} onChange={e => setNewTech(e.target.value)}/>

      <button  type="submit" onClick={handleAddTech}>Adicionar</button>
    </form>
  )
}

export default Component;

1 个答案:

答案 0 :(得分:0)

在您的第二个测试代码中,行({ getByText, getByTestId, getByLabelText } = render(<TechList />))将其断开。删除它,它应该可以正常工作。