简体   繁体   中英

Problem unit testing a delete method with mock service worker (MSW), node and React

I have MSW setup with React and Typescript, the code works in the browser, ie, it deletes the employee, but not in the test, the other tests are working fine. I'm stumped, there's probably something daft that I'm doing, any help would be greatly appreciated
github repo https://github.com/cherry15/cc2022react
handlers.ts


  rest.delete(`${url}/:employeeId`, (req, res, ctx) => {  
    const { employeeId } = req.params
    if (employeeId) {
      const employeeIndex = EmployeesData.findIndex(
        (employee) => employee.id === employeeId.toString()
      )
      if (employeeIndex !== -1) {
        EmployeesData.splice(employeeIndex, 1)
        return res(ctx.status(200))
      } else {
        return res(ctx.status(404))
      }
    }
    return res(ctx.status(400))
  }),

employees.test.tsx

describe('Delete employee', () => {
  test('clicking on the OK button deletes the employee', async () => {
    renderWithProviders(<EmployeeList />)
    await screen.findByRole('heading', { name: /ada lovelace/i })
    await screen.findAllByRole('button', { name: 'Delete employee' })

    fireEvent.click(screen.getAllByRole('button', { name: 'Delete employee' })[0])
    fireEvent.click(await screen.findByText('OK'))
    expect(screen.getByText(/ada lovelace/i)).not.toBeInTheDocument()
  })
})

This isn't exactly a MSW or RTK Query issue. Being that you're performing async operations, you need to await the disappearance of the target element.

test("clicking on the OK button deletes the employee", async () => {
renderWithProviders(<EmployeeList />);

// Wait for ada lovelace to show up to the party!
await screen.findByRole("heading", { name: /ada lovelace/i });
await screen.findAllByRole("button", { name: "Delete employee" });

fireEvent.click(
  screen.getAllByRole("button", { name: "Delete employee" })[0]
);
fireEvent.click(await screen.findByText("OK"));

// Let's wait to make sure she's gone!
await waitForElementToBeRemoved(() =>
  screen.queryByRole("heading", { name: /ada lovelace/i })
);
});

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