我正在尝试为我的反应组件编写单元测试。这是我的组成部分:
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>
);
}
}
在上面的代码中,removeAllSpace是我通过javascript原型扩展创建的函数,如下所示:
String.prototype.removeAllSpaces = function() {
return this.replace(/\s+/g, '');
}
这是我的测试:
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);
});
});
现在,当我运行测试时,我收到以下错误:
TypeError: this.props.channel.removeAllSpaces is not a function
显然它不喜欢我的removeAllSpaces功能..任何想法?
更新:当我删除removeAllSpaces函数时,一切正常
答案 0 :(得分:2)
尝试将removeAllSpaces方法添加到测试文件中的String原型中,我认为应该可行。