我目前正在尝试编写一段代码,测试在React Native中获取组件的API
这是我的代码
import React from 'react';
import renderer from 'react-test-renderer';
import { LoseView } from '../../../components';
import {render, screen, act} from "@testing-library/react-native"
describe('tests of the Lose View', () => {
beforeEach(() => {
global.fetch = jest.fn(() => Promise.resolve({
json: () => Promise.resolve ({
joke: "The Joke"
})
}))
});
it("Loads the joke on mount", async () =>{
await act(async () => renderer.create(<LoseView />));
expect(screen.getByText("The Joke")).toBeInDocument();
})
}
字符串
这是我尝试测试的LoseView组件:
const LoseView = () => {
const [currentJoke, setCurrentJoke] = useState("");
const fetchJokeApi = async () => {
// Fetching data from the API
await fetch("https://v2.jokeapi.dev/joke/Miscellaneous,Pun?blacklistFlags=nsfw,religious,political,racist,sexist,explicit&type=single")
.then((response) => response.json())
.then((data) =>
setCurrentJoke(data.joke),
);
};
useEffect(() => {
fetchJokeApi();
}, [])
return(
<View style={{ flex: 1,alignItems: 'center', justifyContent: 'center'}}>
<Text>you lost!, have a lame consolation joke</Text>
<Text>{currentJoke}</Text>
</View>
);
}
export {LoseView};
型
这个问题依赖于这样一个事实,即测试没有通过,因为测试的expect部分中的“getByText”发送了这个错误:
TypeError: Cannot read property 'getByText' of undefined
型
我的代码出了什么问题?是我构建文本的方式吗?
1条答案
按热度按时间vuv7lop31#
根据此注解,您使用的是
@testing-library/react-native
的^7.2.0版本。升级到10.1.0或更高版本应允许您导入screen
。我还没有验证你的测试除了进口。