如何使用浅(酶)模拟从渲染方法调用的方法
How to mock a method which being called from render method using shallow (enzyme)
我需要模拟 getZvalue,所以当我根据 z 值进行浅层处理时,我会尝试渲染一些不同的东西。我如何测试它。下面是示例代码。
我可以将此方法侦测到 return 一个值
class AbcComponent extends React.Component{
render(){
const z= this.getZValue();
return <div>{z}</div>
}
getZValue(){
//some calculations
}
}
describe('AbcComponent',()=>{
it('Test AbcComponent',()=>{
const wrapper= shallow<AbcComponent/>
})
})
这个怎么样?
import { spy } from 'sinon';
describe('AbcComponent',()=> {
it('Test AbcComponent',()=> {
spy(AbcComponent.prototype, "getZValue");
const wrapper= shallow<AbcComponent/>
expect(AbcComponent.prototype.getZValue.callCount).to.equal(1);
AbcComponent.prototype.getZValue.restore();
})
})
除此之外,您可以使用 return 值进行如下测试,
import { stub } from 'sinon';
describe('AbcComponent',()=> {
it('Test AbcComponent',()=> {
stub(AbcComponent.prototype, "getZValue").returns(10);
const wrapper= shallow<AbcComponent/>
expect(AbcComponent.prototype.getZValue.callCount).to.equal(1);
AbcComponent.prototype.getZValue.restore();
})
})
我需要模拟 getZvalue,所以当我根据 z 值进行浅层处理时,我会尝试渲染一些不同的东西。我如何测试它。下面是示例代码。 我可以将此方法侦测到 return 一个值
class AbcComponent extends React.Component{
render(){
const z= this.getZValue();
return <div>{z}</div>
}
getZValue(){
//some calculations
}
}
describe('AbcComponent',()=>{
it('Test AbcComponent',()=>{
const wrapper= shallow<AbcComponent/>
})
})
这个怎么样?
import { spy } from 'sinon';
describe('AbcComponent',()=> {
it('Test AbcComponent',()=> {
spy(AbcComponent.prototype, "getZValue");
const wrapper= shallow<AbcComponent/>
expect(AbcComponent.prototype.getZValue.callCount).to.equal(1);
AbcComponent.prototype.getZValue.restore();
})
})
除此之外,您可以使用 return 值进行如下测试,
import { stub } from 'sinon';
describe('AbcComponent',()=> {
it('Test AbcComponent',()=> {
stub(AbcComponent.prototype, "getZValue").returns(10);
const wrapper= shallow<AbcComponent/>
expect(AbcComponent.prototype.getZValue.callCount).to.equal(1);
AbcComponent.prototype.getZValue.restore();
})
})