When I write the test by jest and start by yarn jest. Tags has value ""
in <summary>{tags}</summary>
. How emulate value in tags <summary>
than equals "v1.0.0"? Sum up, I get this error:
FAIL src/components/Tags.test.js (10.003 s)
● renders user data
expect(received).toBe(expected) // Object.is equality
Expected: "v1.0.0"
Received: ""
Module Tags.js is:
import { useParams } from 'react-router-dom';
import React, { useEffect, useState } from 'react';
import { GetTags } from '../api/GetTags';
export default function Tags() {
const [isLoading, setLoading] = useState(true);
// const [tags, setTags] = useState([]);
const [tags, setTags] = useState();
const { user, repo } = useParams();
useEffect(() => {
GetTags(user, repo).then(response => {
//response.map((number`enter code here`) => setTags(oldArray => [...oldArray, number.name]));
response.map((tag) => setTags(tag));
setLoading(false);
});
}, []);
return(
<details>
<summary>{tags}</summary>
</details>
)
Test file Tags.test.js is:
import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act } from "react-dom/test-utils";
import routeData from "react-router"
import Tags from "./Tags";
let container = null;
const mockParams = {
user: 'testUser',
repo: 'testRepo'
}
beforeEach(() => {
// подготавливаем DOM-элемент, куда будем рендерить
container = document.createElement("div");
document.body.appendChild(container);
jest.spyOn(routeData, 'useParams').mockReturnValue(mockParams)
});
afterEach(() => {
// подчищаем после завершения
unmountComponentAtNode(container);
container.remove();
container = null;
});
it("renders user data", async () => {
const fakeTag = "v1.0.0";
global.fetch = jest.fn().mockImplementation(() =>
Promise.resolve({
json: () => Promise.resolve(fakeTag)
})
);
// Используем act асинхронно, чтобы передать успешно завершённые промисы
await act(async () => {
render(<Tags />, container);
});
expect(container.querySelector("summary").textContent).toBe(fakeTag);
//expect(container.querySelector("h1").textContent).toBe(fakeTag);
// выключаем фиктивный fetch, чтобы убедиться, что тесты полностью изолированы
global.fetch.mockRestore();
global.fetch.mockClear();
delete global.fetch;
});
Aucun commentaire:
Enregistrer un commentaire