【发布时间】:2020-12-19 06:03:51
【问题描述】:
如果我们将 jest 与 typescript 一起使用,其中使用了交叉点观察器,交叉点观察器的模拟将变得困难。到目前为止,我在:
beforeEach(() => {
// IntersectionObserver isn't available in test environment
const mockIntersectionObserver = class {
observe() {
console.log(this);
}
unobserve() {
console.log(this);
}
disconnect() {
console.log(this);
}
root = null
rootMargin = '0'
thresholds=[1]
takeRecords=() => ([{
isIntersecting: true,
boundingClientRect: true,
intersectionRatio: true,
intersectionRect: true,
rootBounds: true,
target: true,
time: true,
}])
};
window.IntersectionObserver = mockIntersectionObserver;
});
但这仍然会引发错误,例如:
Type 'typeof mockIntersectionObserver' is not assignable to type '{ new (callback: IntersectionObserverCallback, options?: IntersectionObserverInit | undefined): IntersectionObserver; prototype: IntersectionObserver; }'.
The types returned by 'prototype.takeRecords()' are incompatible between these types.
Type '{ isIntersecting: boolean; boundingClientRect: boolean; intersectionRatio: boolean; intersectionRect: boolean; rootBounds: boolean; target: boolean; time: boolean; }[]' is not assignable to type 'IntersectionObserverEntry[]'.
Type '{ isIntersecting: boolean; boundingClientRect: boolean; intersectionRatio: boolean; intersectionRect: boolean; rootBounds: boolean; target: boolean; time: boolean; }' is not assignable to type 'IntersectionObserverEntry'.
Types of property 'boundingClientRect' are incompatible.
Type 'boolean' is not assignable to type 'DOMRectReadOnly'.ts(2322
我可以继续为每个元素添加正确的类型,但有更好的方法吗?
如何在 jest 环境中添加交叉点观察者?我觉得比这样嘲讽要好。
【问题讨论】:
-
如果这使事情变得更加复杂,您不一定需要在模拟中保持类型安全。但在这种情况下,它显示了模拟中的错误。检查developer.mozilla.org/en-US/docs/Web/API/…。 boundingClientRect 等一些属性不是布尔值。此外,将 IntersectionObserver 设为返回 spy 方法的 spy 比使用虚假方法实现的类更有意义。
-
能否请您详细说明一下作为答案,以便未来的开发人员可以轻松理解。请为TS新手写。
标签: typescript mocking jestjs react-testing-library intersection-observer