'Can someone check if my test case is valid or not
i just want to check if this code is written correct. code is working but not sure if it's the correct way to do it.
this is my __test__ file.
import {
rest
} from 'msw'
import {
setupServer
} from 'msw/node'
import {
render,
fireEvent,
screen,
cleanup,
} from '@testing-library/react'
import '@testing-library/jest-dom'
import "whatwg-fetch";
import Fetch from "../Fetch";
afterEach(() => cleanup())
const server = setupServer(
rest.get("https://jsonplaceholder.typicode.com/todos/1",
(req, res, ctx) => {
return res(ctx.json([{
greeting: 'Hello there'
}]));
})
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
test('load and displays heading', async () => {
render( <Fetch url = {
'https://jsonplaceholder.typicode.com/todos/1'
}
/>)
fireEvent.click(screen.getByText('fetch'))
await screen.findByTestId('heading')
})
this is my Fetch component file.
I'm using axios for data fetching here thats the main component i'm trying to be checked.
i just want to check if this code is written correct. code is working but not sure if it's the correct way to do it.
import { useState } from "react";
import axios from "axios";
export default function Fetch({ url }) {
const [users, setUsers] = useState();
async function handleUsers() {
return await axios
.get("https://jsonplaceholder.typicode.com/todos/1")
.then((response) => setUsers(response.data));
}
console.log(users);
return (
<div>
{users ? <h1 data-testid="heading">{users.title}</h1> : null}
<button onClick={handleUsers}>fetch</button>
</div>
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
