StephJ
StephJ

Reputation: 3

Simple React button test fails

Im using jest to test a simple button in React and it keeps failing. My latest iteration complains about render. I'm new to testing and I've been at it for a while and cannot figure this out. What am I missing here?

Here's my App.js


function clickMe() {
  
  alert("Hello")

}

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

    </div>
  )
}

export default App;

Here's my 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)
})

Upvotes: 0

Views: 92

Answers (2)

StephJ
StephJ

Reputation: 3

Not exactly the same but something like this also worked

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)
})

Upvotes: 0

You can simulate some events with the enzyme library

For this first install this by npm, then import that

import {shallow} from 'enzyme';

After using this structure to simulate a click on a bottom

Create a wrapper

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

This creates a simulation of render components and gives you the capacity to simulate events, this method is working in my project counterApp

test('Click', ()=>{

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

Upvotes: 1

Related Questions