0

Im trying to get a react testing library test going but having lots of issues

import React from 'react'
import Header from './Header'
import {render, cleanup} from '@testing-library/react'

test("Renders's the header and required inputs", () => {
  const { getByTestId } = render(<Header/>);
  const Header = component.getByTestId ('header');
  expect(Header.textContent).toBe("Shipping Label")
})

The component exports Header.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • 1
    Maybe it's confused because you have both a global `import Header from './Header'` **and** a second `const Header = component.getByTestId ('header');` that is scoped to the anonymous function in your test? Which `Header` are you exporting? – antun May 11 '21 at 17:33
  • 1
    Define "lots of issues." – Dave Newton May 11 '21 at 17:48
  • I was following the syntax pretty directly from this tuturial about header testing https://www.youtube.com/watch?v=GLSSRtnNY0g – VibrationPositive May 11 '21 at 17:51
  • saying component is not defined – VibrationPositive May 11 '21 at 17:51
  • also the header declared but not being read – VibrationPositive May 11 '21 at 17:52
  • gettestbyid also being affected – VibrationPositive May 11 '21 at 17:52
  • `getByTestId` is a function of `screen` from testing-library IIRC, not something returned by `render`. You might want to also check out the [@testing-library/react docs](https://testing-library.com/docs/queries/about/). It's difficult to tell if your `
    ` component is being imported correctly, but it does complicate things when you create a *new* `Header` when you try to access whatever `component` is (don't see that anywhere in the code). I'd consider taking a brief step back to learn about testing-library before going much further.
    – Dave Newton May 11 '21 at 18:00
  • @DaveNewton this code is directly from a tutorial so its hard to get it going without having a very basic test like this work. – VibrationPositive May 13 '21 at 21:45
  • I’m not sure what to tell you—I would look at the docs or a another tutorial. – Dave Newton May 14 '21 at 14:35

2 Answers2

1
import React from 'react'
import Header from './Header'
import {render} from '@testing-library/react'

test("Renders's the header and required inputs", () => {
 const { getByText, getByTestId } = render(<Header />);
  expect(getByTestId("header")).toBeTruthy();
  expect(getByText("Shipping Label")).toBeTruthy();
})

Try something like this, I think you are trying to use "component" from enzyme or such, and it's not defined.

Take a look at the testing library cheat sheet

Nick Foden
  • 1,108
  • 11
  • 12
0

You will need to import React at the top of the file which may cause issues if you don't with rendering things.

import React from "react";
James Paterson
  • 2,652
  • 3
  • 27
  • 40