javascript - 如何使用 Jest 将 prop 中的 spyOn 方法传递给组件?
问题描述
背景:
我的测试框架是 Jest 和 Enzyme。我有一个名为的组件Lazyload
,它与LazyloadProvider
using耦合React.ContextAPI
。我想编写一个测试来保证 组件内部 prop 方法componentDidMount
的on已被调用。使用 Jest spy 我希望这是有效的Lazyload
this.props.lazyload.add()
hasBeenCalledWith(this.lazyRef)
我开玩笑说能够窥探 Lazyload 的register
方法;但是,我无法弄清楚如何监视内部道具方法this.props.lazyload.add
。
问题:
我如何写一个笑话间谍this.props.lazyload.add
并确保它被调用this.lazyRef
?
class Lazyload extends Component<LazyloadProps, LazyloadState> {
lazyRef: ReactRef;
constructor(props) {
super(props);
this.lazyRef = createRef();
}
componentDidMount() {
this.register()
}
register() { // not spy on this.
this.props.lazyload.add(this.lazyRef); // spyOn this
}
}
测试:
describe('lazyload', () => {
let provider;
beforeEach(() => {
provider = shallow(
<LazyloadProvider>
<p>Wow</p>
</LazyloadProvider>
).instance();
});
it('should register a lazyloader with add', () => {
const spy = jest.spyOn(Lazyload.prototype, 'register');
const wrapper = shallow(
<Lazyload lazyload={provider.engine}>
<p>doge</p>
</Lazyload>
).instance();
expect(spy).toHaveBeenCalled(); // this works however it's a better test to spy on the this.prop.lazyload.add method.. but how?
});
})
解决方案
您可以在道具中传递存根 ,并检查toHaveBeenCalledWith匹配器是否接受instance()的:add
lazyload
lazyref
describe('lazyload', () => {
it('should add ref', () => {
const lazyloadStub = {
add: jest.fn();
};
const wrapper = shallow(
<Lazyload lazyload={lazyloadStub}>
<p>doge</p>
</Lazyload>
);
expect(lazyloadStub.add).toHaveBeenCalledWith(wrapper.instance().lazyRef);
});
})
推荐阅读
- php - 使用 html encode(yii2) 显示数据库中的数据
- python - 带有 python 子进程的 WSL
- nlp - 有没有办法将 spacy 标签列入白名单?
- google-apps-script - 无法在 Google 表格中设置值
- php - 在 WooCommerce 电子邮件通知中将发件人姓名更改为客户账单全名
- html - 是否可以在 transform: translateX 中使用 %vw?
- python - pybind11:通过值/引用将 numpy 数组传递给 c++
- css - 修复了滚动时移动设备上的背景缩放
- java - 使用 Spring Boot 在控制器中调用 rest void 方法
- php - 如何在 php 中将 DateTime 从 yyyy-mm-dd hh:mm:ss 转换为 yyyymmddThhmmssZ