我有一个反应组件,它有一个方法
export class Hit extends React.Component {
constructor(props) {
super(props);
this.triggerClick= this.triggerClick.bind(this);
}
triggerClick(event) {
this.props.triggerClick(event.target.click);
}
render() {
return (
....................................
<input ........ onChange={this.triggerClick} />
.............................................
);
}
}
我想检查是否正在调用 triggerClick(event) 方法。因此,我正在粘贴与此相关的代码。虽然如果您在 hitComponent 的日志中看到如下内容,
onChange: [功能:绑定triggerClick]
间谍日志说它没有被调用。不知道我哪里出错了。
let mockFunction = sinon.fake();
let hitComponent = renderShallow(<Hit ........ triggerClick= {mockFunction}/>)
let spy = sinon.spy(Hit.prototype, 'triggerClick');
console.log(hitComponent)
console.log(spy)
o / p:命中组件:
[ { '$$typeof': Symbol(react.element),
type: 'input',
key: null,
ref: null,
props:
{ type: '.....',
checked: true,
onChange: [Function: bound triggerClick] },
.....}]
o / p:间谍:
{ [Function: proxy]
isSinonProxy: true,
called: false,
notCalled: true,
calledOnce: false,
calledTwice: false,
calledThrice: false,
callCount: 0,
firstCall: null,
secondCall: null,
thirdCall: null,
lastCall: null,
args: [],
returnValues: [],
thisValues: [],
exceptions: [],
callIds: [],
errorsWithCallStack: [],
displayName: 'triggerClick',
toString: [Function: toString],
instantiateFake: [Function: create],
id: 'spy#1',
stackTraceError:
Error: Stack Trace for original
at wrapMethod ..........
restore: { [Function] sinon: true },
wrappedMethod: [Function: triggerClick]
}
有一个辅助类可以使用 react-test-renderer
import ShallowRenderer from 'react-test-renderer/shallow';
function renderShallow(component) {
const shallowRenderer = new ShallowRenderer();
shallowRenderer.render(component);
return shallowRenderer.getRenderOutput();;
}
export {renderShallow}