Hamed Minaee Hamed Minaee -4 years ago 89
React JSX Question

unite testing of react component fails for not recognizing a built in function

I am trying to write unit test for my react component. Here is my component:

import React from "react";

require("../../../../css/ads/ads.css");
export class Ads extends React.Component {


render() {
return (
<div className="ads-container txt-flex-alignment">
<a id={"dummyAdsLink" + this.props.channel.removeAllSpaces().toLowerCase() + this.props.adsId}
href="#"
target="_top"><img
id={"dummyAdsImg" + this.props.channel.removeAllSpaces().toLowerCase() + this.props.adsId}
className="img-responsive" src={this.url}
/></a>


</div>


);
}


}

In the above code removeAllSpace is a function I created by the extension of javascript prototype as follows:

String.prototype.removeAllSpaces = function() {
return this.replace(/\s+/g, '');
}


And here is my test:

import React from 'react';
import expect from 'expect.js';
import {shallow} from 'enzyme';
import {Ads} from "../../src/app/components/story/ads/Ads";
import renderer from 'react-test-renderer';

describe('<Ads />', () => {

it('should render 1 <a /> components', () => {
const wrapper = shallow(<Ads channel="whatevername"/>);
expect(wrapper.find('a')).to.have.length(1);
});
});


Now when I run the test I get the following error:

TypeError: this.props.channel.removeAllSpaces is not a function


Apparently it does not like my removeAllSpaces function.. any idea?

Update: when I remove the removeAllSpaces function everything works fine

Answer Source

Try to add the removeAllSpaces method to String prototype in you test file, i think that should work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download