Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/411.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ReactJS::Jest测试::“;TypeError:无法读取属性';然后';“未定义”的定义;_Javascript_Reactjs_Testing_Jestjs - Fatal编程技术网

Javascript ReactJS::Jest测试::“;TypeError:无法读取属性';然后';“未定义”的定义;

Javascript ReactJS::Jest测试::“;TypeError:无法读取属性';然后';“未定义”的定义;,javascript,reactjs,testing,jestjs,Javascript,Reactjs,Testing,Jestjs,我目前在为在线学习任务编译测试时遇到一些问题,无法查看天气应用程序的fetch()函数是否正常工作 我已经使用useffect()钩子从OpenWeatherAPI获取数据,以便在API的URL发生变化时存储和呈现数据 我是一个新的笑话测试,并尝试了一些事情,以下教程和其他来源,但不幸的是没有任何成功。我当前的解决方案返回以下错误:“TypeError:无法读取未定义的'then'属性” 请看下面我的代码: App.js // Imported hooks and react libraries

我目前在为在线学习任务编译测试时遇到一些问题,无法查看天气应用程序的fetch()函数是否正常工作

我已经使用useffect()钩子从OpenWeatherAPI获取数据,以便在API的URL发生变化时存储和呈现数据

我是一个新的笑话测试,并尝试了一些事情,以下教程和其他来源,但不幸的是没有任何成功。我当前的解决方案返回以下错误:“TypeError:无法读取未定义的'then'属性”

请看下面我的代码:

App.js

// Imported hooks and react libraries.
import React, { useState, useEffect } from 'react';
// Imported stylesheet.
import './App.css';
// Imported components.
import Header from './components/Header';
import Footer from './components/Footer';
// Imported countries from i18n-iso-countries to get the iso code and return the country name in English.
import countries from 'i18n-iso-countries';
// Imported icons from Font Awesome.
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
  faCloudSunRain,
  faHandHoldingWater,
  faHandSparkles,
  faMapMarkerAlt,
  faSearchLocation,
  faTemperatureHigh,
  faTemperatureLow,
  faWind
} from '@fortawesome/free-solid-svg-icons';

countries.registerLocale(require('i18n-iso-countries/langs/en.json'));

function App() {
  // Setting the initial states of the app to store the response and the locations. Using the useState hook to set the data. Showing Durban as 
  // an example.
  const [apiData, setApiData] = useState({});
  const [getState, setGetState] = useState('Durban');
  const [state, setState] = useState('Durban');

  // Constructing the API URL and accessing the key via the process.env variable.
  const apiKey = process.env.REACT_APP_API_KEY;
  const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${state}&APPID=${apiKey}`;
  console.log (process.env.REACT_APP_API_KEY);

  // Using the useEffect hook to fetch the data from the API to store and render once the API's URL changes.
  useEffect(() => {
    fetch(apiUrl)
      .then((res) => res.json())
      .then((data) => setApiData(data));
  }, [apiUrl]);

  // Constructed an input handler to get the data once requested and to store in the getState.
  const inputHandler = (event) => {
    setGetState(event.target.value);
  };

  // Constructed a submit handler to handle the request once the search button is clicked.
  const submitHandler = () => {
    setState(getState);
  };

  // Constructed a kelvin to celsius converter to output the temperature in celsius.
  const kelvinToCelsius = (k) => {
    return (k - 273.15).toFixed(2);
  };

  // Constructed a miles to kilometers converter to output the temperature in kilometers.
  const milesToKilometers = (k) => {
    return (k * 3.6).toFixed(2);
  };

  // Created a function to capitalize the first letters of each part of the countries' names.
  function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  };

  // Returning the data. Included the React Bootstrap stylesheet's link and called the "Header" and "Footer" components below. I also called the
  // following from the API:

  // {apiData.weather[0].icon} - The icon displaying the current conditions.
  // {apiData.name} - The city's name.
  // {countries.getName(apiData.sys.country, 'en', { select: 'official', })} - The country's name with the first letters capitalized.
  // {kelvinToCelsius(apiData.main.temp_min)} - The minimum temperature.
  // {kelvinToCelsius(apiData.main.temp_max)} - The maximum temperature.
  // {kelvinToCelsius(apiData.main.feels_like)} - The "feels like" temperature, taking into account the temperatures and conditions.
  // {apiData.weather[0].main} - The summarized condition.
  // {capitalizeFirstLetter(apiData.weather[0].description)} - The full condition's description.
  // {apiData.main.humidity} - The humidity percentage.
  // {milesToKilometers(apiData.wind.speed)} - The wind speed.

  // Called the inputHandler (input section) and submitHandler (button) to get the current state's values and added Font Awesome icons. Also 
  // added a loading message for if the page load takes a while. Currently only shows if there is no input or upon refresh.
  return (
    <div className="App">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css"></link>
      <Header />

      <div className="container">
        <div className="searchsection">
          <label htmlFor="location-name">Enter Location:</label>
          <input
            type="text"
            id="location-name"
            onChange={inputHandler}
            value={getState}
          />
          <button onClick={submitHandler}><FontAwesomeIcon icon={faSearchLocation} /></button>
        </div>

        <div className="mt-3 mx-auto" style={{ width: '60vw' }}>
          {apiData.main ? (
            <div id="weathercontainer">
              <div id="mainweather">
                <img
                  src={`http://openweathermap.org/img/wn/${apiData.weather[0].icon}@2x.png`}
                  alt="weather status icon"
                  className="weather-icon"
                />
                <p className="h2">{kelvinToCelsius(apiData.main.temp)}&deg;C</p>
                <h3><FontAwesomeIcon icon={faMapMarkerAlt} /> {apiData.name}</h3>
                <h3>{countries.getName(apiData.sys.country, 'en', { select: 'official', })}</h3>
              </div>

              <div className="temperatureconditions">
                <div id="temperature">
                  <h5>Temperature:</h5>
                  <p><FontAwesomeIcon icon={faTemperatureLow} /> {kelvinToCelsius(apiData.main.temp_min)}&deg;C</p>
                  <p><FontAwesomeIcon icon={faTemperatureHigh} /> {kelvinToCelsius(apiData.main.temp_max)}&deg;C</p>
                  <p><FontAwesomeIcon icon={faHandSparkles} /> Feels like: {kelvinToCelsius(apiData.main.feels_like)}&deg;C</p>
                </div>
                <div id="conditions">
                  <h5>Conditions:</h5>
                  <p><FontAwesomeIcon icon={faCloudSunRain} /> {apiData.weather[0].main}: {capitalizeFirstLetter(apiData.weather[0].description)}</p>
                  <p><FontAwesomeIcon icon={faHandHoldingWater} /> Humidity: {apiData.main.humidity}%</p>
                  <p><FontAwesomeIcon icon={faWind} /> Wind Speed: {milesToKilometers(apiData.wind.speed)} km/h</p>
                </div>
              </div>
            </div>
          ) : (
            <h1 id="loading">Weather Bot is Loading...</h1>
          )}
        </div>
      </div>
      <Footer />
    </div>
  );
}

// Exported App to Index.js.
export default App;
import React from 'react';
import App from '../App';
import { render, screen, act } from '@testing-library/react';

global.fetch = jest.fn(() =>
    Promise.resolve({
        json: () =>
            Promise.resolve({
                value: "Durban"
            }),
    })
);

describe("App", () => {
    it("loads Durban city name", async () => {
        await act(async () => render(<App />));
        expect(screen.getByText("Durban")).toBeInTheDocument();
    });
});
//导入的钩子和react库。
从“React”导入React,{useState,useffect};
//导入的样式表。
导入“/App.css”;
//进口部件。
从“./components/Header”导入标题;
从“./components/Footer”导入页脚;
//从i18n iso国家/地区导入国家/地区,以获取iso代码并返回英文国家/地区名称。
来自“i18n iso国家”的进口国;
//从字体导入图标。
从'@fortawesome/react fontawesome'导入{FontAwesomeIcon};
进口{
太阳雨,
Fahand HoldingWater,
法汉德闪闪发光,
法马佩拉特,
faSearchLocation,
华氏温度高,
华氏温度低,
法文
}来自“@fortwome/free solid svg icons”;
registerLocale(需要('i18n-iso-countries/langs/en.json');
函数App(){
//设置应用程序的初始状态以存储响应和位置。使用useState挂钩设置数据。显示为
//举个例子。
const[apiData,setApiData]=useState({});
const[getState,setGetState]=useState('德班');
const[state,setState]=useState('德班');
//构造API URL并通过process.env变量访问密钥。
const apiKey=process.env.REACT\u APP\u API\u KEY;
常量apiUrl=`https://api.openweathermap.org/data/2.5/weather?q=${state}&APPID=${apiKey}`;
console.log(process.env.REACT\u APP\u API\u KEY);
//使用useEffect钩子从API获取数据,以便在API的URL更改后存储和呈现。
useffect(()=>{
获取(APIRL)
.然后((res)=>res.json())
。然后((数据)=>setApiData(数据));
},[apirl]);
//构造了一个输入处理程序,用于在请求时获取数据并存储在getState中。
常量inputHandler=(事件)=>{
setGetState(event.target.value);
};
//构建了一个提交处理程序,用于在单击搜索按钮后处理请求。
常量submitHandler=()=>{
设置状态(getState);
};
//构造了一个开尔文到摄氏度的转换器,以摄氏度为单位输出温度。
常数kelvinToCelsius=(k)=>{
返回(k-273.15)。固定(2);
};
//构建了一个英里到公里的转换器,以公里为单位输出温度。
常量里程=(k)=>{
返回(k*3.6)。固定(2);
};
//创建了一个函数,将国家名称每个部分的首字母大写。
函数首字母大写(字符串){
返回string.charAt(0.toUpperCase()+string.slice(1);
};
//返回数据。包括React引导样式表的链接,并调用下面的“页眉”和“页脚”组件。我还调用了
//API的以下内容:
//{apiData.weather[0].icon}-显示当前条件的图标。
//{apidat.name}-城市名称。
//{countries.getName(apiData.sys.country,'en',{select:'official',})-首字母大写的国家名称。
//{kelvinToCelsius(apiData.main.temp_min)}-最低温度。
//{kelvinToCelsius(apiData.main.temp_max)}-最高温度。
//{kelvinToCelsius(apiData.main.feels_like)}-考虑到温度和条件,“感觉就像”温度。
//{apiData.weather[0].main}-汇总的条件。
//{capitalizeFirstLetter(apiData.weather[0].description)}-完整条件的描述。
//{apiData.main.湿度}-湿度百分比。
//{英里公里(apiData.wind.speed)}-风速。
//调用inputHandler(输入部分)和submitHandler(按钮),以获取当前状态的值并添加字体图标
//如果页面加载需要一段时间,则添加加载消息。当前仅在没有输入或刷新时显示。
返回(
输入位置:
{apiData.main(

{kelvinToCelsius(apiData.main.temp)}°;C

{apiData.name} {countries.getName(apiData.sys.country,'en',{select:'official',})} 温度: {kelvinToCelsius(apiData.main.temp_min)}°;C

{kelvinToCelsius(apiData.main.temp_max)}°;C

感觉像:{kelvinToCelsius(apiData.main.Feels_-like)}°;C

条件: {apiData.weather[0]。main}:{capitalizeFirstLetter(apiData.weather[0]。description)}

湿度:{apiData.main.湿度}%

风速:{milestokems(apiData.Wind.Speed)}km/h

) : ( 天气机器人正在加载。。。 )} ); } //已将应用程序导出到Index.js。 导出默认应用程序;
App.Fetch.React.test.js

// Imported hooks and react libraries.
import React, { useState, useEffect } from 'react';
// Imported stylesheet.
import './App.css';
// Imported components.
import Header from './components/Header';
import Footer from './components/Footer';
// Imported countries from i18n-iso-countries to get the iso code and return the country name in English.
import countries from 'i18n-iso-countries';
// Imported icons from Font Awesome.
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
  faCloudSunRain,
  faHandHoldingWater,
  faHandSparkles,
  faMapMarkerAlt,
  faSearchLocation,
  faTemperatureHigh,
  faTemperatureLow,
  faWind
} from '@fortawesome/free-solid-svg-icons';

countries.registerLocale(require('i18n-iso-countries/langs/en.json'));

function App() {
  // Setting the initial states of the app to store the response and the locations. Using the useState hook to set the data. Showing Durban as 
  // an example.
  const [apiData, setApiData] = useState({});
  const [getState, setGetState] = useState('Durban');
  const [state, setState] = useState('Durban');

  // Constructing the API URL and accessing the key via the process.env variable.
  const apiKey = process.env.REACT_APP_API_KEY;
  const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${state}&APPID=${apiKey}`;
  console.log (process.env.REACT_APP_API_KEY);

  // Using the useEffect hook to fetch the data from the API to store and render once the API's URL changes.
  useEffect(() => {
    fetch(apiUrl)
      .then((res) => res.json())
      .then((data) => setApiData(data));
  }, [apiUrl]);

  // Constructed an input handler to get the data once requested and to store in the getState.
  const inputHandler = (event) => {
    setGetState(event.target.value);
  };

  // Constructed a submit handler to handle the request once the search button is clicked.
  const submitHandler = () => {
    setState(getState);
  };

  // Constructed a kelvin to celsius converter to output the temperature in celsius.
  const kelvinToCelsius = (k) => {
    return (k - 273.15).toFixed(2);
  };

  // Constructed a miles to kilometers converter to output the temperature in kilometers.
  const milesToKilometers = (k) => {
    return (k * 3.6).toFixed(2);
  };

  // Created a function to capitalize the first letters of each part of the countries' names.
  function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  };

  // Returning the data. Included the React Bootstrap stylesheet's link and called the "Header" and "Footer" components below. I also called the
  // following from the API:

  // {apiData.weather[0].icon} - The icon displaying the current conditions.
  // {apiData.name} - The city's name.
  // {countries.getName(apiData.sys.country, 'en', { select: 'official', })} - The country's name with the first letters capitalized.
  // {kelvinToCelsius(apiData.main.temp_min)} - The minimum temperature.
  // {kelvinToCelsius(apiData.main.temp_max)} - The maximum temperature.
  // {kelvinToCelsius(apiData.main.feels_like)} - The "feels like" temperature, taking into account the temperatures and conditions.
  // {apiData.weather[0].main} - The summarized condition.
  // {capitalizeFirstLetter(apiData.weather[0].description)} - The full condition's description.
  // {apiData.main.humidity} - The humidity percentage.
  // {milesToKilometers(apiData.wind.speed)} - The wind speed.

  // Called the inputHandler (input section) and submitHandler (button) to get the current state's values and added Font Awesome icons. Also 
  // added a loading message for if the page load takes a while. Currently only shows if there is no input or upon refresh.
  return (
    <div className="App">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css"></link>
      <Header />

      <div className="container">
        <div className="searchsection">
          <label htmlFor="location-name">Enter Location:</label>
          <input
            type="text"
            id="location-name"
            onChange={inputHandler}
            value={getState}
          />
          <button onClick={submitHandler}><FontAwesomeIcon icon={faSearchLocation} /></button>
        </div>

        <div className="mt-3 mx-auto" style={{ width: '60vw' }}>
          {apiData.main ? (
            <div id="weathercontainer">
              <div id="mainweather">
                <img
                  src={`http://openweathermap.org/img/wn/${apiData.weather[0].icon}@2x.png`}
                  alt="weather status icon"
                  className="weather-icon"
                />
                <p className="h2">{kelvinToCelsius(apiData.main.temp)}&deg;C</p>
                <h3><FontAwesomeIcon icon={faMapMarkerAlt} /> {apiData.name}</h3>
                <h3>{countries.getName(apiData.sys.country, 'en', { select: 'official', })}</h3>
              </div>

              <div className="temperatureconditions">
                <div id="temperature">
                  <h5>Temperature:</h5>
                  <p><FontAwesomeIcon icon={faTemperatureLow} /> {kelvinToCelsius(apiData.main.temp_min)}&deg;C</p>
                  <p><FontAwesomeIcon icon={faTemperatureHigh} /> {kelvinToCelsius(apiData.main.temp_max)}&deg;C</p>
                  <p><FontAwesomeIcon icon={faHandSparkles} /> Feels like: {kelvinToCelsius(apiData.main.feels_like)}&deg;C</p>
                </div>
                <div id="conditions">
                  <h5>Conditions:</h5>
                  <p><FontAwesomeIcon icon={faCloudSunRain} /> {apiData.weather[0].main}: {capitalizeFirstLetter(apiData.weather[0].description)}</p>
                  <p><FontAwesomeIcon icon={faHandHoldingWater} /> Humidity: {apiData.main.humidity}%</p>
                  <p><FontAwesomeIcon icon={faWind} /> Wind Speed: {milesToKilometers(apiData.wind.speed)} km/h</p>
                </div>
              </div>
            </div>
          ) : (
            <h1 id="loading">Weather Bot is Loading...</h1>
          )}
        </div>
      </div>
      <Footer />
    </div>
  );
}

// Exported App to Index.js.
export default App;
import React from 'react';
import App from '../App';
import { render, screen, act } from '@testing-library/react';

global.fetch = jest.fn(() =>
    Promise.resolve({
        json: () =>
            Promise.resolve({
                value: "Durban"
            }),
    })
);

describe("App", () => {
    it("loads Durban city name", async () => {
        await act(async () => render(<App />));
        expect(screen.getByText("Durban")).toBeInTheDocument();
    });
});
从“React”导入React;
从“../App”导入应用程序;
从'@testing library/react'导入{render,screen,act};
global.fetch=jest.fn(()=>
承诺,决心({
json:()=>
承诺,决心({
价值:“德班”
}),
})
);
描述(“应用程序”,()