More Testing


Uncategorized

Updated Jun 3rd, 2022

React testing library docs here. And GitHub here. And query reference here.

React docs has some testing recipes here.

But first. What and why test? Read this.

describe("Overall name of your test", ()=> {
  it("should do this", () => {
    // write your code here
  })
})

Assertions

expect(true).toBeTruthy()

Export function so you can import them into your test files.

Dependency Inversion. Will make code easier to “spy” on.

jest.fn()

Test that a function is invoked.

Pro tip, make sure that a passing test fails when you comment out the function (or any crucial code).

Test out diferent scenarios. In this example, test 1 is an email was sent to a failing student and test 2 was an email was not sent because no one failed.

expect(mailer.Fn).toHaveBeenCalled()

Some More React testing Stuff:

.test()
.render()
.expect()
.toBeEnabled()
.toBeDisabled()
.toBe()
screen.getByRole()
.findByRole()
userEvent.type(screen.getByPlaceholderText())

Make so the test will pass, pass the test, then change to make sure if it fails of it is not true.

React testing library has a recommended testing priority with regard to your queries. form elements should first test label text.

Arrange, Act, Assert Pattern

unit tests
integration tests

not everyone agrees where the line between the two is

What Are We Testing Exactly?

Make sure your app does what it should do

Handle loading

Fail as expected

Components exist as expected.

Hit a submit button and make sure that the text “required” shows up if the fields are left blank.

Hit a submit button with text and make sure that a new todo with that text appears.

What is the Main Comp to Render in Next JS App?

It is “Home” by default

Test File Organization

Each component has a folder with comp, styles, and tests or a separate folder for “__tests__?”

Not sure yet.

If A Test Renders A Comp That is Expecting Props, It Needs Those Props

Ca we pass dummy data? Like “jest.fn(),” empty functions and default values.

TS kind of complicates this more right?

On Button Click, Ensure Function Called or Function Implemented?

// before describe
const whatEvs = jest.fn()
//when rendering comp
render(<MyComp whatEvs={whatEvs} />)
//
fireEvent.click(whatEvsButton)
expect(whatEvs).toHaveBeenCalledTimes(1)

Difference Between getBy, findBy, queryBy

findBy is for async.

queryBy is same as getBy but getBy throws exception and queryBy returns null

The Loading… Text

Testing for loading text can be challenging because it is not there by default and shows for a very brief time.

First off, I found this gem, “needs to be async for this to work, otherwise it doesn’t make sense to have a loading state at all, as either success or error message will be shown almost immediately.”

Do We Need to Unmount or Unrender after Test?

RTL does this cleanup automatically for us.

Sources

Web Dev Junkie

Dude in 2018 here

Continuous Delivery here

LamaDev May 2022 – fantastic here