简体   繁体   中英

How can I test a button onClick which uses props.history for it's function in rtl?

I'm using react testing library and I want to test a button which is:

<button data-testid="btn" onClick={() => props.history.push(`/post/${value}`)} > Search </button>
<input data-testid="input" type="text" value={value} onChange={(e) => handle(e.target.value)} />

and I test it's onClick function like this:

test('Button should navigate the url when enabled', () => {
        render(<Home />);
        const input = screen.getByTestId('input');
        const btn = screen.getByTestId('btn');
        fireEvent.change(input, { target: { value: '12' } });
        fireEvent.click(btn);
    });

But it gives me an error:

    TypeError: Cannot read property 'push' of undefined

      19 |                              <button
      20 |                                      data-testid="btn"
    > 21 |                                      onClick={() => props.history.push(`/post/${value}`)}
         |                                                                   ^
      22 |                                      disabled={!value}
      23 |                                      type="submit"
      24 |                              >

The app itself works fine when I npm start but fails only when testing it. How can I solve this push of undefined?

You have to pass props to the rendered component, in this case - <Home /> :

import history from 'history' // Or a file you made that contains an instance of history

test('Button should navigate the url when enabled', () => {
        render(<Home history={history} {...otherProps} />);
        const input = screen.getByTestId('input');
        const btn = screen.getByTestId('btn');
        fireEvent.change(input, { target: { value: '12' } });
        fireEvent.click(btn);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM