Home > Blockchain >  React testing with Jest and Enzyme: How to write test for connected components with API call and pro
React testing with Jest and Enzyme: How to write test for connected components with API call and pro

Time:05-03

I am fairly new to testing React applications with Jest and Enzyme. I am trying to test some connected components, but don't understand how to mock data for those. I have an API call and use props. Here are my files:

News Page

import React, { Component }  from 'react';
import './news.style.css';
import NewsList from '../../components/news-list/news-list.component';
import { SearchBar } from '../../components/search-bar/search-bar.component';
import Header from '../../components/header/header.component';
import { NewsFooter } from '../../components/news-footer/news-footer.component';

class News extends Component {
    constructor() {
        super();
        this.state = {
          news: [],
          searchField: '',
          topics: ''
        };
      }
    
      componentDidMount() {
        fetch('https://sheltered-earth-94987.herokuapp.com/news')
        .then(response => response.json())
        .then(news => this.setState({ news: news}));
      }
    
      render() {
        const { news, searchField, topics } = this.state;
        const filteredNewsname = news
        .filter(news => news.news_topic.toLowerCase().includes(topics.toLowerCase()))
        .filter(news => news.news_headline.toLowerCase().includes(searchField.toLowerCase()));
        return (
          <div>
          <Header/>
          <h1 className="pageheadline">News</h1>
          <SearchBar
          placeholder='Search News'
          handleChange= {e => this.setState({ searchField: e.target.value})}
          />
          <div className="newslist">
          <NewsList news={filteredNewsname}>
          </NewsList>
          </div>
          <div className="newsfooter">
          <NewsFooter
          handleClick= {e => this.setState({ topics: e.target.id})}
          />
          </div>
          </div>
        );
      }
      
    }
  export default News;

NewsList Component

import React from 'react';
import './news-list.style.css';
import { NewsCard } from '../news-card/news-card.component';
import { Link } from 'react-router-dom';

const NewsList = props => {
    return <div className='news-list'>
        {
          props.news.map(newsentry => <Link to={`/news/${newsentry.news_id}`}>
          <NewsCard key={newsentry.news_id} newsentry={newsentry}/></Link>)
        }
    </div>;
};

export default NewsList;  

NewsCard Component

import React from 'react';
import './news-card.style.css';

export const NewsCard = props => (
    <div className='news-card-container'>
        <img className="newsimg" alt="Newsimage" src={ props.newsentry.news_header_image}></img>
        <div className="newsinfo">
            <h4 className="newstitle"> { props.newsentry.news_headline } </h4>
            <p className="teaser">{props.newsentry.news_teaser}</p>
            <p className="author">By {props.newsentry.news_author} </p>
        </div>
        <p className="newstopic">#{props.newsentry.news_topic}</p>
        
    </div>
)

How can I test the NewsList and the NewsCard Components with mocked data?

CodePudding user response:

Before rendering components in test block; you can provide a new, mockup variable to your component.

Example:

<NewsCard key={..} newsentry={mockupNewsentry}/> with mockupNewsentry being your mockup data variable.

Longer example:

  test("renders singleitem with data", async () => {
    const mockupData = {
      name: "Homer Simpson",
      job: "Nuclear Safety Inspector",
      id: "14",
    };

    render(
          <SingleItem data={mockupData} />
    );
    
    const element = await screen.findByText(/Homer Simpson/i);
    expect(element).toBeInTheDocument();
    
  });

CodePudding user response:

Check out this package. It will mock the network layer. Everyone is using this one for integration testing of components.

https://mswjs.io

  • Related