【发布时间】:2021-05-20 09:03:48
【问题描述】:
我在尝试使用 Jasmine 模拟 Angular 的 LocationChangeListener 界面时遇到了麻烦。
这就是我的代码所做的:
onPopState(fn: LocationChangeListener): void {
this.platformLocation.onPopState((ev: LocationChangeEvent): void => {
... here I do the stuff I actually want to test ...
}
}
所以基本上,我正在尝试使用 LocatioNChangeListener 调用 onPopState,这样我就可以测试函数内部的所有逻辑。 我已经嘲笑了 LocationChangeEvent:
const locationChangeEventMock: LocationChangeEvent = {
type: 'typemock',
state: 1,
};
但是我所有模拟 LocationChangeListener 的努力都是徒劳的......这真的可能吗?由于 TypeScript 的接口“问题”?
编辑:经过一些调试,看起来 ev: LocationChangeEvent 不是来自 LocationChangeListener(显然),所以我需要,不知何故,触发LocationChangeEvent?
到目前为止,我对其进行了一些代码重构:将我想要的代码提取到一个方法中,然后调用该方法......但仍然很好奇如何测试它。
【问题讨论】:
-
如何在方法中使用
fn? -
在方法的最后,像这样:
fn(ev);。对我来说真正重要的是能够使用LocationChangeEvent,因为这是我在方法内部使用的,所以我确实需要一个可调用的LocationChangeListener的模拟,它调用LocationChangeEvent模拟。 -
我添加了一个答案并创建了一个模拟示例。 codesandbox.io/s/fomfx 你可以在 Typescript 操场上查看。这个模拟是有效的。
标签: angular unit-testing mocking jasmine