如何模拟返回订阅的方法



我现在有一个方法,我想测试和模拟,但不确定如何进行

interaction
.onEvent('DO_SOMETHING')
.subscribe(async (items: Array<Item>) => {
console.log(items)
});
export declare class Interaction {
onEvent<T = any>(eventName: string): Subscriber<T>;
}
export interface Subscriber<T> {
subscribe(value?: Callback<[T]>, error?: Callback<any>, complete?: Callback<[]>): Unsubscriber;
}

我试着这样嘲笑

interaction: {
onEvent: jest.fn().mockReturnValue({ subscribe: jest.fn() }),
},

测试本身只是运行一个快照,该快照在渲染时运行模拟交互。

const store = createStore();
mount(
<StoreProvider value={store}>
<Plugin interaction={interaction} />
</StoreProvider>,
);
await async.delay(100);
expect(store.state).toMatchSnapshot();

但我收到一个错误,告诉我错误:未捕获[TypeError:无法读取未定义的属性'subscribe']。有人能为我遗漏的东西提供建议吗?

要在模拟实现中创建可观察的返回,可以执行以下操作:

jest.spyOn(yourObject, 'method').mockImplementation(() => of(response))

of((是rxjs包中的一个函数,从值中创建可观测值。来源:https://rxjs.dev/api/index/function/of

最新更新