简单的 React 按钮测试失败

Simple React button test fails

我在 React 中使用 jest 测试一个简单的按钮,但一直失败。我的最新迭代抱怨渲染。我是测试新手,我已经测试了一段时间,但无法弄清楚。我在这里错过了什么?

这是我的 App.js


function clickMe() {
  
  alert("Hello")

}

function App() {
  return (
    <div className="App">
      <button id="btn" onClick={clickMe}>Click Me!!</button>

    </div>
  )
}

export default App;

这是我的 App.test.js

import React from 'react'
import {render} from 'react-dom'
import App from './App'


test("Click", () => {
  const {container} = render(<App />)

  const button = getByTestId(container, 'btn')
  fireEvent.click(button)
})

你可以用酶库模拟一些事件

为此首先通过 npm 安装它,然后导入那个

import {shallow} from 'enzyme';

使用此结构模拟底部点击后

创建包装器

let wrapper = shallow(<App />);
beforeEach( ()=>{
    wrapper = shallow(<CounterApp />);
});

这会创建渲染组件的模拟,并为您提供模拟事件的能力,此方法在我的项目 counterApp 中有效

test('Click', ()=>{

    wrapper.find('button').at(0).simulate('click');
    
    expect(//The action of your botton).toBe(//the result expected);
});

不完全相同,但类似的方法也有效

import { shallow } from 'enzyme'
import { configure } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import App from './App'

configure({ adapter: new Adapter() })

it('renders the link inside the output area', () => {
  const output = shallow(<App />)
  expect(output.find('div').find('button').length).toEqual(1)
})