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')
Related
I am new to react storybook and have created relatively simple stories so far as mentioned below:
import React from 'react';
import { action } from '#storybook/addon-actions';
export default {
title: "Test"
}
export const test = () => <textarea onClick={action('textarea clicked')}>Hong test from me</textarea>;
export const input = () => <input type="text"></input>;
With this knowledge, I want to go ahead and create complex stories i.e. as shown in the image below:
Is there any tutorial which will help me achieve this.
Thanks
I am not sure if I understood your question correctly, but I will try to give you an answer.
What we usually do with storybook stories is to create the story and then import a complex component inside it.
import React from 'react';
import { storiesOf } from '#storybook/react';
import { CustomComponent } from '../src';
storiesOf('CustomComponent', module)
.add('Custom Component story 1', () => (
<CustomComponent />
));
I'm writing unit tests for a React application using Cypress. I wish to use the 'cypress-react-unit-test' to test individual components.
I am only importing React, cypress-react-unit-test (in support/index.js) and the component itself.
I have a simple component (test.js)
import React, { Component } from 'react';
import "./test.css"
class Test extends Component{
render(){
return(
<h1>Testing {this.props.name}</h1>
)
}
}
export default Test;
along with a test.scss containing
h1 {
color: blue
}
When I start the test runner I get an error preparing test file referring to the test.css file
Can someone explain what is going on here?
Same issue as this cypress ParseError on css content, but I am already using the cypress-react-unit-test package. As said there, if I comment out the import css file in the component file, the component renders without any styling. But what if I want to assert a heading's colour for example?
My starting testcode
import React from 'react'
import Test from '../../../../src/components/test.js'
describe('testing React', ()=>{
it('should react', ()=>{
cy.mount(<Test name="Nrd" />)
cy.contains('Testing')
})
})
[Create-React-App] Jest and Enzyme(3.9.0) cant seem to find my <Button/> Element from Auth.jx container..
The application should render the Auth container if(!isAuthernticated) and the button should be disabled if no input is supplied.
I tried ShallowWrapper::dive() but i get a TypeError
TypeError: SHallowWrapper::dive() can only be called on components
Auth.jsx
//...
let errorMessage = null;
let button=<Button id='Disabled' btnType="Success" disabled={false}>Disabled</Button>;
let authRedirect = null;
if (this.props.isAuthenticated) {
authRedirect = <Redirect to={this.props.authRedirectPath}/>
}
if (this.state.controls.username.value && this.state.controls.password.value){
button=<Button id='Login' btnType="Success">Login</Button>
}
return (
<div>
{authRedirect}
<form onSubmit={this.handleSubmit}>
{form}
{button}
</form>
</div>
)
}
//...
Auth.test.js
import React from 'react';
import {shallow} from 'enzyme';
import Auth from '../containers/Auth/Auth';
import Button from '../components/Button/button';
import Input from '../components/Input/input';
describe('<Auth/>',() =>{
let wrapper;
beforeEach(()=>{
wrapper=shallow(<Auth authRedirectPath='/' isAuthenticated={false}/>).dive()
})
//Test 1
it('should render disabled button if no input has been specified ',()=>{
expect(wrapper.find(Button).text()).toEqual('Disabled')
});
})
I don't believe you should be calling dive() on the wrapper in your test. Instead, you should shallow render your wrapper and then call dive() or render() on the found Button to test for its text.
So, first:
wrapper = shallow(<Auth authRedirectPath='/' isAuthenticated={false} />)
Then, when you want to find(Button) and test for its text when rendered, you would do either of the following:
expect(wrapper.find(Button).dive().text()).toEqual('Disabled')
// OR
expect(wrapper.find(Button).render().text()).toEqual('Disabled')
To demonstrate this, I've re-created a skeleton of your code here at this code sandbox. You can see, specifically in Auth.test.js how I have modified your original test with my code lines above. If you click on "Tests" in the bottom toolbar, you'll see that the test passes.
If you go into Auth.jsx and you change the username and password values - thereby affecting the Button text - then the test will fail.
My comment above has explored that you use Redux's connect HOC on the component. That's why you can't access the desired component since that's a level deeper within the tree.
I'd suggest reading my article on Medium in which you can find some details about the actual problem and also the appropriate solution.
EDIT
If you're still experiencing the same issue, I'd suggest the following:
Let's suppose that your Auth component is something like this.
import React, { Component } from 'react';
import { connect } from 'react-redux';
export class Auth extends Component {
// Something happens here.
}
export default connect(mapStateToProps, mapDispatchToprops)(Auth);
Notice that I used the export keyword in both cases. That being said, you can test the proper component without any connection to Redux and it also reduces the generated tree.
Pay attention to import the named export class within the test file:
...
import { Auth } from './Auth';
...
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.
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.