lundi 29 juin 2020

how to test if parameter is undefined and defined react jest testing

With Jest testing I was trying to test if the parameters are undefined or defined. So it can test if the data-testid is available in the DOM. So therefore I created one mockApi that contains objects and one mockApi that contains nothing in order to test both scenarios, but cannot figure out how to do that so this test will incapsulate all the needs I want.

export const Result = ({ data, city }) => {
    if(data === undefined || city === undefined) {
        return (
            <div data-testid="empty-array"></div>
        )
    } else {
        return (
            <div data-testid="weather-array">
                <div className="city-name">{city}</div>
                <div className="weather-info">
                    <div className="temperature">{data.temp}</div>
                    <div>{data.weather[0].main}</div>
                    <div>{data.weather[0].description}</div>
                    <img src={`http://openweathermap.org/img/w/${data.weather[0].icon}.png`} alt={city + ' weather status'}/>
                </div>
            </div>
        )
    }
}

// index.test.js

import React from "react"
import { render } from "@testing-library/react";
import { Result } from './index.js';
import { Provider } from "react-redux";
import { store } from "../../Store";
import { screen } from "@testing-library/dom";

import { weatherData } from '../../mock/mockAPI';
import { 
    emptyWeatherApi, 
    emptyCityApi 
} from '../../mock/emptyApi';

test("It should check if there is no data in Result component", () => {
    render(
        <Provider store={store}>
            <Result city={emptyCityApi} />
        </Provider>
    )
    const checkWeatherData = screen.getAllByTestId("empty-array");
    expect(checkWeatherData).toHaveLength(1);
});

test("It should check if there is data in Result component", () => {
    render(
        <Provider store={store}>
            <Result 
                data={weatherData} 
            />
        </Provider>
    )
    const checkWeatherData = screen.getByTestId("weather-array");
    console.log(checkWeatherData);
    // expect(checkWeatherData).toHaveLength(1);
});

Aucun commentaire:

Enregistrer un commentaire