我有以下反应成分,我试图用酶和开胃液进行单元测试。
import React from 'react';
import { Subject } from 'rxjs/Subject';
import { connect } from 'react-redux';
import styles from './IncrementalSearch.scss';
import { performIncrementalStoreSearch } from './IncrementalSearchActions';
export class IncrementalSearch extends React.Component {
constructor(props) {
console.log('constructor');
super(props);
this.onSearch$ = new Subject();
this.onChange = this.onChange.bind(this);
}
componentDidMount() {
this.subscription = this.onSearch$
.debounceTime(300)
.subscribe(debounced => {
this.props.onPerformIncrementalSearch(debounced);
});
}
componentWillUnmount() {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
onChange(e) {
const newText = e.target.value;
this.onSearch$.next(newText);
}
render() {
return (
<div className={styles.srchBoxContaner}>
<input
className={styles.incSrchTextBox}
type="text" name="search" placeholder="Search.."
onChange={this.onChange}
/>
</div>
);
}
}
const mapDispatchToProps = (dispatch) => ({
onPerformIncrementalSearch: (searchText) => {
dispatch(performIncrementalStoreSearch(searchText));
}
});
const IncrementalSearchComponent = connect(null, mapDispatchToProps)(IncrementalSearch);
export default IncrementalSearchComponent;
我的单元测试如下
import React from 'react';
import { mount } from 'enzyme';
import sinon from 'sinon';
import { IncrementalSearch } from './IncrementalSearch';
describe('<IncrementalSearch />', () => {
it('calls componentDidMount', () => {
sinon.spy(IncrementalSearch.prototype, 'componentDidMount');
const wrapper = mount(<IncrementalSearch />);
expect(IncrementalSearch.prototype.constructor.calledOnce).to.equal(true);
});
});
但是,当我运行单元测试时,我收到以下错误
TypeError: Cannot read property 'debounceTime' of undefined
如果我在componentDidMount中注释掉所有内容,那么我会收到以下错误
<IncrementalSearch /> › calls componentDidMount
TypeError: Cannot read property 'equal' of undefined
at Object.<anonymous> (src/components/common/incrementalSearch/IncrementalSearch.test.js:10:89)
at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
at process._tickCallback (internal/process/next_tick.js:103:7)
<IncrementalSearch />
× calls componentDidMount (29ms)
为了让它运行,我还需要做一些额外的设置吗?
答案 0 :(得分:0)
我认为你的问题有两个。
首先,我确认onSearch $确实存在,并在测试中完成您的期望。我感觉有些东西没有在那里得到恰当的定义。
关于第二个问题,这是人们在使用酶时常犯的错误。
expect(...).to.be(...)
是Enzyme(Chai)使用的语法,Jest使用不同的Expect库
你可以在这里看到差异:
http://chaijs.com/api/bdd/
https://facebook.github.io/jest/docs/expect.html
因此expect(...).to
未定义,因此to.equal
在未定义时调用equal
。将其更改为expect(...).toEqual(...)
,您应该没问题