Test logo component in React Jest - reactjs

I've a requirement same as
Jest + Enzyme: How to test an image src?
where I want to test Logo component that only consist image 'logo.png'. I've tried the solution answered by thierno.
Logo component
import React from 'react';
import PropTypes from 'prop-types';
export default function LogoJCpenney1({ logopath, logowidth }) {
return (
<img src={logopath} alt="logo" width={logowidth} className="logoOriginal"/>
);
}
LogoJCpenney1.propTypes = {
/** original logo path of JCPenney */
logowidth: PropTypes.string
};
LogoJCpenney1.defaultProps = {
className:"logoOriginal"
};
Test component
import React from 'react';
import {configure, shallow} from 'enzyme';
import LogoJCpenney1 from '../LogoJCpenney1/LogoJCpenney1';
import Adapter from 'enzyme-adapter-react-16';
configure({adapter:new Adapter()});
import logoImage from "./../../containers/assets/img/jcpenneylogo1.png";
describe("<LogoJCpenney1 />", () => {
it("renders an image", () => {
const logo = shallow(<LogoJCpenney1 logoImage={logoImage} logowidth="50" />);
expect(logo.find("img").prop("src")).toEqual(logoImage);
});
});
Test result
Any help is appreciated.

You are sending a logoImage prop to your LogoJCpenney1 component, but what the component actually wants is a logopath prop (which it will use as the image's src). You shouldn't use the path to import in the actual logo image. You should just pass in the path as the logopath prop.
The reason you are getting Expected string but received undefined is because logo.find("img").prop("src") is, in fact, undefined... since you did not provide a logopath prop to your component.
Perhaps something like this:
import React from 'react';
import { configure, shallow } from 'enzyme';
import LogoJCpenney1 from '../LogoJCpenney1/LogoJCpenney1';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
const logopath = "../../containers/assets/img/jcpenneylogo1.png";
describe("<LogoJCpenney1 />", () => {
it("renders an image", () => {
const logo = shallow(<LogoJCpenney1 logopath={logopath} logowidth="50" />);
expect(logo.find("img").prop("src")).toEqual(logopath);
});
});
Based on the other StackOverflow post you referenced, you might be thinking, "But I don't just want to test that src is set correctly. I want to test that the img actually shows the jcpenneylogo1.png file."
I would advise against this. You don't need to test that an <img> properly displays an image file when given a src. That's third-party stuff that React and your browser have already taken care of, and it's not your job to test those things.
Since you're unit testing LogoJCpenney1, you just need to make sure that, when you pass LogoJCpenney1 a prop called logopath, then it renders an img that has a src equal to that logopath.

Related

How do I Import a manually mocked module with mocked data using jest and enzyme?

My test doesn't seem to importing my manual mock under __mocks__/Auth.js.
I have a module that I use, Auth.js in my react application, App.js. I am trying to mock that module using a manual mock by making a mocked file under __mocks__/Auth.js. My __mocks__ is at the same file level as App.js and Auth.js.
I have a repo here: https://github.com/chaselw/reactTesting
Or my test is below:
import React from 'react';
import Enzyme, { shallow, mount } from 'enzyme';
import EnzymeAdapter from 'enzyme-adapter-react-16'
import App from './App';
Enzyme.configure({ adapter: new EnzymeAdapter() });
test('logged in false', () => {
jest.mock('./Auth.js'); //Trying to get `auth.isLoggedIn() === false`
const wrapper = mount(<App />);
console.log(wrapper.debug())
expect(wrapper.exists("[data-test='Logged-In-False']")).toBe(true);
})
Expected result is that the test would return a "Logged-In-False" div from Login module after the if check on auth.isLoggedIn(). However I get the "true" div back.
In the test if I do: console.log(wrapper.auth.isLoggedIn()), it returns .isLoggedIn() is undefined.
I am new to React, jest and enzyme. I have no idea what is wrong, any help would be great! Thanks.
The solution was simple. jest.mock('./Auth.js') needs to be not inside a test, but rather at the top level as the imports.
import React from 'react';
import Enzyme, { shallow, mount } from 'enzyme';
import EnzymeAdapter from 'enzyme-adapter-react-16'
import App from './App';
jest.mock('./Auth');
Enzyme.configure({ adapter: new EnzymeAdapter() });
test('logged in false', () => {
//Trying to get `auth.isLoggedIn() === false`
const wrapper = mount(<App />);
console.log(wrapper.debug())
expect(wrapper.exists("[data-test='Logged-In-False']")).toBe(true);
})

jest with enzyme testing shallow stucks

I am trying to test a component in react native, but it gets stuck on the shallow test. If I pass an incorrect component, the test fails, but if I pass a react-native text component it gets stuck.
import React from "react";
import Enzyme, {shallow, mount} from "enzyme";
import Screen from 'react-native-login'
import Adapter from "enzyme-adapter-react-16"
import { configure } from 'enzyme'
import {Text} from 'react-native'
configure({ adapter: new Adapter() })
test('render with react-native component', () => {
const wrapper = shallow(<Text />); // Hangs
})

Testing returned value of component method with value passed through

Hi I'm trying to make a test for a component method that is passed in a number and returns a string. This is my first time writing test in react and I couldn't find any examples of what to do in my situation.
my code
import moment from "moment";
import React from 'react';
class ReactPage extends React.Component {
//some other functions
//turn number into money (returns string)
commafyMoney = (money) => {
return "$"+ money.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
}
//return fancy react webpage
render(){
return(
//stuff
);
}
}
export default ReactPage;
this is my attempt of testing the returned value
import {shallow, mount, render, configure} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import ReactDOM from 'react-dom';
import ReactPage from './App';
it('commafyMoney(number)', () => {
const wrapper = shallow(<ReactPage />);
expect(wrapper.instance().commafyMoney(1234.56)).toEqual("$1,234.56");
});
Does anyone know how I can fix this test so it works?
Option 1: wrapper.instance()
You're missing some of the waffle required to set up enzyme.
import React from 'react'; // React must be in scope any time you write jsx.
configure({ adapter: new Adapter() }); // Let enzyme use the adapter.
Add these lines after your imports and the test should pass. (Assuming jest is configured properly.)
Option 2: Don't render the component.
Since the method you're testing does not directly affect the rendering of your component, you can just get an instance of the component without rendering.
import ReactPage from './App';
it('commafyMoney(number)', () => {
const page = new ReactPage;
expect(page.commafyMoney(1234.56)).toEqual("$1,234.56");
});
This raises the question of why is the method defined in the class instead of being a utility function imported from somewhere else. You would preferably move the method to another module where its easier to test.

Unit testing image tag with image object

i have following reactjs code snippet:
import lionIcon from 'assets/images/lion.svg';
import dogIcon from 'assets/images/dog.svg';
<img
className="animal-btn-img"
src={isLion ? lionIcon : dogIcon}
/>
how do i unit test that based on 'isLion' prop, appropriate animal object is set on the img tag.?
let img = wrapper.find('.animal-btn-img');
console.log(img.prop('src'));
the above console.log returns only empty object as {}
try shallow from enzyme, it worked well for me
import React from 'react'
import {shallow} from 'enzyme'
import Testor from '../components/Testor'
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
it('should see image source', () => {
const container = shallow(<Testor/>)
expect(container.find('img').props().src).toEqual('http://google.com/')
})

React js unit testing with enzyme

Hi guys i am new to react can anyone help me to write unit test for the below code .. i want to test if link is redirecting properly..
Here is my code ..
import React { Component } from 'react';
import {Link} from 'react-router';
import './App.css';
class Home extends Component {
render() {
return (
<Link to='/college/masters/cs' className="student">
<div className="centered">
<h2 className="Branch">Branch</h2>
</div>
</Link>
);
}
}
My test
import React from 'react';
import { mount, shallow } from 'enzyme';
import {expect} from 'chai';
import 'ignore-styles';
import Home from '../src/Home';
describe('<Home/>', function () {
it('should have a Link', function () {
const wrapper = shallow(<Home/>);
expect(wrapper.find('Link')).to.have.length(1);
});
});
Please help me to write test if link is redirecting properly..
Thank you
Well, try this out. It should work.
You merely need to check whether you are passing the valid to property with a relevant value to the Link component. That's it. You don't need to check whether it takes you to the given url, since it is the functionality of the Link component and they should have tests to verify that. If you need that then what you are writing is not a unit test, it is called an e2e. You may need selenium or so in doing that.
expect(wrapper.find('Link').props().to).to.eql('/college/masters/cs')

Resources