类型错误:无法读取未定义的属性“getByText”

时间:2021-07-29 01:57:07

标签: react-native unit-testing jestjs jsx

我目前正在尝试编写一个代码来测试在 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};

问题依赖于测试未通过的事实,因为测试的期望部分中的“getByText”发出此错误:

TypeError: Cannot read property 'getByText' of undefined

我的代码有什么问题?是我构造文本的方式吗。

0 个答案:

没有答案