Sinon:Test React组件方法正在调用函数pass作为道具(Mocha+Chai+Sinon用于单元测试)



我有一个react组件,它有一个方法

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(事件(方法。因此,我正在粘贴与此相关的代码。尽管如果你在hitComponent的日志中看到以下内容,

onChange:[函数:绑定触发器点击]

间谍日志说没有人叫它。不确定我哪里错了。

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:hitComponent:

[ { '$$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测试渲染器

import ShallowRenderer from 'react-test-renderer/shallow';

function renderShallow(component) {
const shallowRenderer = new ShallowRenderer();
shallowRenderer.render(component);
return  shallowRenderer.getRenderOutput();;
}
export {renderShallow}

triggerClick在类实例化时绑定。在那之后,它就不能在Hit.prototype上被窥探或嘲笑了。

它应该是:

let spy = sinon.spy(Hit.prototype, 'triggerClick');
let hitComponent = renderShallow(<Hit triggerClick= {mockFunction}/>)

或者:

let hitComponent = renderShallow(<Hit triggerClick= {mockFunction}/>)
sinon.spy(hitComponent.instance(), 'triggerClick');

最新更新