Unit Testing functional components with Jest and Enzyme - reactjs

I have written test case for the post.js to find 3 p tag but it's throwing an error. How do I properly test this component?
Post.js
import React from 'react';
import './Post.css';
const Post = (props) => {
const displayPosts = (props) => {
const { posts } = props;
if ( posts.length > 0 ){
return(
posts.map( (post) => {
return(
<div className = "Post">
<p className = "name"> <b>Name :</b> {post.name}</p>
<p className = "email"> <b> Email :</b> {post.email}</p>
<p className = "body"> <b> Body :</b> {post.body}</p>
</div>
)
})
)
}
}
return (
<div className = "Posts">
{ displayPosts(props) }
</div>
)
}
export default Post;
Post.test.js
import React from "react";
import Adapter from "enzyme-adapter-react-16";
import { shallow, configure } from "enzyme";
import Post from "./Post";
configure({ adapter: new Adapter() });
describe("Post", () => {
it("includes three paragraphs", () => {
const wrapper = shallow(<Post />);
expect(wrapper.find("p")).toHaveLength(3);
});
});

I'm new to testing myself. However, at a quick glance your testing from a shallow perspective while your 'p' tags are actually rendered/nested deeper (in your 'displayPosts' component) than where you are testing. I would bet that if you console.log the wrapper object in your test code you would see a single div logged.
From the enzyme docs: "Shallow rendering is useful to constrain yourself to testing a component as a unit, and to ensure that your tests aren't indirectly asserting on behavior of child components."

Related

Displaying audio waveforms in React

So i´m building this webpage which allow users to upload a song, and the displayind that sound as a card on the home-page. Sort of like Soundcloud...
Im just getting to learn React, after coming from html, css and JS. So please understand im new to this all.
I´ve been researched the topic alot, and no one has seemed to work for me.
Ive been trying howler.js, and wavesurfer.js, without any luck of displaying waveforms.
have anyone else tried doing this before? someone who could maybe help out?
import { ErrorResponse } from '#remix-run/router';
import React from 'react'
import wavesurfer from 'wavesurfer.js'
import "./css/audio.css"
import { useRef } from 'react';
export const AudioVisualizer = (props) => {
// the homepage has a function to map through all the objects in the
// database, and in return i get every object. I then get the link from each
// object and pass this link into this function as an ARgument.
let link = props;
const audioRef = useRef();
console.log("here is props: " + link);
try {
var audioTrack = wavesurfer.create({
container: audioRef,
wavecolor: "#eee",
progressColor: "red",
barWidth: 2,
});
audioTrack.load(link);
} catch (ErrorResponse) {
console.error("Something happened..");
return ErrorResponse;
};
return (
<div className='audio' ref={audioRef}>
</div>
)
}
From there I have the actual Home.js page where I want to display the returned from the function above.
the home.js file looks like this:
import React, { useEffect, useState } from 'react';
import '../components/css/home/home.css';
import {collection, getDocs, onSnapshot} from 'firebase/firestore';
import {db} from '../firebase'
import { useNavigate } from 'react-router-dom';
import {ClipLoader} from 'react-spinners';
import {AudioVisualizer} from "../components/audioVisualizer"
const Home = () => {
const [songs, setSongs] = useState([]);
const [loading, setLoading] = useState(false);
const navigate = useNavigate();
useEffect(() => {
setLoading(true);
const retrieveSongs = onSnapshot(
collection(db, "songs"),
(snapshot) => {
let arrayList = [];
snapshot.docs.forEach((doc) => {
arrayList.push({ id: doc.id, ...doc.data() });
});
setSongs(arrayList);
setLoading(false);
},
(error) => {
console.log(error);
}
);
return () => {
retrieveSongs();
};
}, []);
return (
<div className='home_wrapper'>
<>
{loading ?
<ClipLoader color="#36d7b7" />
:
<div className='homepage_container'>
{ songs.map((data) => {
return (
<article key={data.id} className='card'>
<div className='card_content'>
<img className='card_image' src={data.image} />
<div className='song_info'>
<h2>{data.title}</h2>
<h4>{data.artist}</h4>
</div>
<div className='audioplayer'>
{AudioVisualizer(data.audio)}
{/* <ReactAudioPlayer src={data.audio} autoPlay controls/> */}
{/* <Waveform className="audio_file" audio={data.audio}/> */}
</div>
</div>
<div className='card_content_extra'>
<button onClick={() => navigate('/update/${data.id}')}>Edit</button>
<button >Listen</button>
</div>
{/* <div id="waveform"></div>
<button class="btn btn-primary" onclick="wavesurfer.playPause()">
<i class="glyphicon glyphicon-play"></i>Play/Pause
</button> */}
</article>
)
})}
</div>
}
</>
</div>
)
}
export default Home
UPDATE::
So as i described in my comment. When i am mapping through the songs object from my database, the waveform wont display. When i pass a direct link to the component it works. but when im passing my object "audio", and getting the value, , it will not show the waveform. When i try to console.log(data.audio) // it returns undefined.
see for yourself: As you can see from the console.log, it acts weird..
The reference to the DOM element is accessed by the .current property Not the reference object created by React.
You could use the useEffect hook, to load the data.
Then create the AudioVisualizer Component in the JSX react way and pass the link to the wavesurfer.
Also the wavesurfer dom object need to have some size.
Have a look at this mini example:
import React from 'react';
import ReactDOM from 'react-dom/client';
import { useRef, useEffect } from 'react';
import wavesurfer from 'wavesurfer.js'
const AudioVisualizer = (props) => {
const audioRef = useRef();
useEffect(()=>{
if (audioRef.current){
let audioTrack = wavesurfer.create({
container: audioRef.current,
});
audioTrack.load(props.link);
}
})
return <div style={{minWidth: "200px"}} className='audio' ref={audioRef}></div>
}
function App(props) {
return (
<div className='App'>
<AudioVisualizer link={"https://actions.google.com/sounds/v1/science_fiction/creature_distortion_white_noise.ogg"}></AudioVisualizer>
</div>
);
}
ReactDOM.createRoot(
document.querySelector('#root')
).render(<App />)

Pass value from parent to child component with React

I trying to display the rating of a query in my React App. But I'm not sure if I understand how to handle the state.
This is my query component:
import React, { Component, useRef, useState, useEffect } from 'react';
import { render } from 'react-dom';
import InputSearchLandlord from './search'
import './style.css'
import SimpleRating from '../components/star_display'
import ReactStars from 'react-rating-stars-component'
import './style.css'
const HandleSearch = () => {
const [ratingValue, setRating] = useState(0)
const [name, searcName] = useState("")
const nameForm = useRef(null)
const average = arr => arr.reduce( ( p, c ) => p + c, 0 ) / arr.length;
const ratings = []
const displayComment = async() => {
try {
const form = nameForm.current
const name = form['name'].value
searchName(name)
const response = await fetch(`localhost`)
const jsonData = await response.json()
getComments(jsonData)
comments.forEach(e => {
console.log(e.rating)
ratings.push(e.rating)
})
const rating = average(ratings) //Avg of all rating associated with the search
console.log(rating) //Should be pass to Rating component
setRating(rating)
} catch (error) {
console.log(error.message)
}
}
return(
<div className="container">
<div className="form-group">
<h1 className="text-center mt-5">SEARCH</h1>
<form ref={nameForm} className="mt-5">
<InputSearch name={'name'}/>
<div className="d-flex justify-content-center">
<button type="submit" className="d-flex btn btn-primary" onClick={displayComment}>Search</button>
</div>
</form>
<div>
<div className='container'>
<h1>{name}</h1>
<SimpleRating data={ratingValue}
/>
</div>
<div className='container'>
{comments.map(comment => (
<div className="commentSection">
<a>
{comment.problem}
</a><br/>
<a>
Posted on : {comment.date}
</a>
</div>
))}
</div>
</div>
</div>
</div>
)
}
export default HandleSearch;
And this is my Rating component:
import React, { useState } from 'react';
import { render } from 'react-dom';
import ReactStars from 'react-rating-stars-component'
import './style.css'
import HandleSearch from '../pages/handleSearch'
export default function SimpleRating(rating) {
const [ratingValue, setRating] = useState(0)
const options = {
value: ratingValue, //Should use the value from the Search component
a11y: true,
isHalf: true,
edit: false,
};
console.log(options.value)
if (options.value == 0) return null //if rating value = 0 doesn't display the component
return (
<div className="starComponent">
<ReactStars {...options}/>
</div>
);
}
So I trying to pass the value computed in the Search component to the Rating component. Before any query is made with the Search component, the value should be 0 and hidden.
What am I missing ?
Its to do with your props. In your parent component you create a prop called data so in your rating component you need to extract that value from props
// HandleSearch Component
<SimpleRating data={ratingValue}
export default function SimpleRating(props) {
const { data } = props
// You can also just say props.data
... rest of your component
}
Currently you are actually defining the props in your SimpleRating component but you are calling them rating (it doesn't actually matter what you call it but commonly its called props) and that is an object that contains all of the props that you pass into that component.

Is it Possible to use Enzyme testing with Next js (SSR)?

It's My first Nextjs project with SSR.
When Integrating Enzyme For Reactjs UI Testing. it could not run due to "React' refers to a UMD global, but the current file is a module. Consider adding an import instead."
but it's works when i am using normal Reactjs Component(Functional or Class). Anyone Please give suggestions.
SandBox Link - https://codesandbox.io/s/currying-moon-gdk09
Full code From GitHub - https://github.com/Rizz13/nextJs-with-Enzyme
to run testing Use "npm test"
pages/Index.tsx
import Head from 'next/head'
import Link from 'next/link'
import { GetStaticProps } from 'next'
export default function Home({
allPostsData
}: {
allPostsData: {
title: string
id: string
}[]
}) {
return (
<>
<Head>
<title>Sample Page</title>
</Head>
<section className="icon-stars">
<p>[Your Self Introduction]</p>
<p>
(This is a sample website - you’ll be building a site like...)
</p>
</section>
<section>
<h2>Blog</h2>
<ul>
{allPostsData.map(({ id, title }) => (
<li key={id}>
<Link href="#">
<a>{title}</a>
</Link>
<br />
</li>
))}
</ul>
</section>
</>
)
}
export const getStaticProps: GetStaticProps = async () => {
const allPostsData = [{id: 0, title:"Sample1"}, {id: 1, title:"Sample2"}]
return {
props: {
allPostsData
}
}
}
_tests_/Index.tsx
import * as React from 'react'
import { expect as expect1 } from 'chai';
import IndexPage from '../pages/index'
import {/*mount,*/ shallow} from 'enzyme'
const setUp1 = (data) => {
return shallow(<IndexPage {...data} />);
}
let wrapper;
describe('props Check', () => {
beforeEach(() => {
wrapper = setUp1({});
});
it('should render an `.icon-stars`', () => {
expect1(wrapper.find('.icon-stars')).to.have.length(1);
});
});
When I using the Above Code Testing could not run due to below Error.
tests/Index.tsx
import * as React from 'react'
import { expect as expect1 } from 'chai';
import IndexPage from '../pages/index'
import {/*mount,*/ shallow} from 'enzyme'
const setUp1 = (data) => {
return shallow(<IndexPage {...data} />);
}
let wrapper;
describe('props Check', () => {
beforeEach(() => {
wrapper = setUp1(allPostsData={[]});
});
it('should render an `.icon-stars`', () => {
expect1(wrapper.find('.icon-stars')).to.have.length(1);
});
});
You have to pass props inside the testing component & use
import * as React from 'react'
In pages/Index.tsx for rendering react components

Enzyme unit test is passing test when it should fail

I'm trying to test a component it has two props title, and url.
I'm unsure how to pass mock data, i made an attempt but it passes but im pretty sure its not reading whats in the data object
Both tests are passing.
Card.js
import React, {Component} from 'react';
const Styles = {
width: '300px',
height: '300px'
}
class Card extends React.Component {
render() {
return (
<div>
{/* Renders title of the GIY */}
<h1>{this.props.title}</h1>
<div >
<img alt="" src={this.props.url}/>
</div>
</div>
);
}
}
export default Card;
Card.test.js
import React from 'react';
import ReactDOM from 'react-dom';
import {shallow} from 'enzyme';
import Card from './Card';
describe('Should render Card Component', ()=> {
it('should render card component', ()=> {
const component = shallow(<Card />);
})
});
describe('Should render title/ url prop', ()=>{
it('should render title /url prop', ()=>{
// trying to mock data for the Card component
const data = {
title: "owl",
url:"https://giphy.com/gifs/bird-owl-qISaMW1xwmvNS"
}
const component = shallow(<Card title={data.title} url={data.url}/>)
})
})
You're not making any assertions. You need to expect some result to happen.
Card.js (this can be a pure function if it doesn't require state)
import React from "react";
import PropTypes from "prop-types";
const styles = {
width: "300px",
height: "300px"
};
const Card = ({ title, url }) =>
title && url ? ( // if a title and url are passed in, return <div>...</div>, else return "null"
<div className="card">
<h1>{title}</h1>
<div>
<img alt="" src={url} styles={styles} />
</div>
</div>
) : null;
// PropTypes will throw a warning if either of them is missing
PropTypes.propTypes = {
title: PropTypes.string.isRequired,
url: PropTypes.string.isRequired
};
export default Card;
Card.test.js
import React from "react";
import { shallow } from "enzyme";
import Card from "../index";
// we define initial props (empty strings)
const initialProps = {
title: "",
url: ""
};
// we shallow wrap the Card while passing in the "initialProps"
const wrapper = shallow(<Card {...initialProps} />);
// we define some props that will be passed in during our second test
const nextProps = {
title: "owl",
url: "https://media.giphy.com/media/qISaMW1xwmvNS/giphy.gif"
};
describe("Card Component", () => {
afterAll(() => wrapper.unmount());
it("shouldn't render a card without the required props", () => {
expect(wrapper.type()).toBeNull();
});
it("should render a card if the required props are present", () => {
wrapper.setProps({ ...nextProps }); // we update the component with "nextProps"
expect(wrapper.find("div.card")).toHaveLength(1); // expect "div.card" to be present
expect(wrapper.find("h1").text()).toContain(nextProps.title); // expect the "h1" element to contain "owl"
expect(wrapper.find("img").prop("src")).toBe(nextProps.url); // expect the "img"'s src to be "https://media.giphy.com/media/qISaMW1xwmvNS/giphy.gif"
});
});
Working example: https://codesandbox.io/s/k35zpqwk97

React component test with enzyme

I have a component like this:
component.js
import React from "react";
import PropTypes from "prop-types";
const Test = ({ text }) => (
<div>
{text.split("\n").map((item, key) => {
return (
<span key={key}>
{item}
<br />
</span>
);
})}
</div>
);
Test.propTypes = {
text: PropTypes.string.isRequired
};
export default Test;
How do i write component test for this react component using enzyme? I am new to react and enzyme. Any help will really appreciable.
This could be a test using mocha:
import {shallow} from 'enzyme'
import assert from 'assert'
import Test from './Test'
describe('component Test', () => {
it('should show a span for each line of "text" prop', () => {
const text = `foo
bar
`
const wrapper = shallow(<Test text={text} />)
const spans = wrapper.find('span')
assert.equal(spans.length, 2)
assert.equal(spans.at(0).text(), 'foo')
assert.equal(spans.at(1).text(). 'bar')
})
it('should throw if "text" prop is not provided', () => {
assert.throws(() => {
shallow(<Text />)
})
})
})
Here is shamelessly taken example of testing dom using enzyme + jest (from jest web site):
// __tests__/CheckboxWithLabel-test.js
import React from 'react';
import {shallow} from 'enzyme';
import CheckboxWithLabel from '../CheckboxWithLabel';
test('CheckboxWithLabel changes the text after click', () => {
// Render a checkbox with label in the document
const checkbox = shallow(
<CheckboxWithLabel labelOn="On" labelOff="Off" />
);
expect(checkbox.text()).toEqual('Off');
checkbox.find('input').simulate('change');
expect(checkbox.text()).toEqual('On');
});
I recommend you to go though the link I gave - it contains nice examples of testing react components using Jest + Enzyme.

Resources