如何模拟返回订阅的方法
How to mock a method that is returning a subscribe
我目前有一个方法想要测试和模拟,但不确定如何去做
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();
但我收到一条错误消息,告诉我 错误:未捕获 [类型错误:无法读取未定义的 属性 'subscribe']。有人可以就我遗漏的内容提出建议吗?
要创建一个在模拟实现中返回的可观察对象,您可以这样做:
jest.spyOn(yourObject, 'method').mockImplementation(() => of(response))
of() 是 rxjs 包中的一个函数,它根据值创建可观察对象。资料来源:https://rxjs.dev/api/index/function/of
我目前有一个方法想要测试和模拟,但不确定如何去做
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();
但我收到一条错误消息,告诉我 错误:未捕获 [类型错误:无法读取未定义的 属性 'subscribe']。有人可以就我遗漏的内容提出建议吗?
要创建一个在模拟实现中返回的可观察对象,您可以这样做:
jest.spyOn(yourObject, 'method').mockImplementation(() => of(response))
of() 是 rxjs 包中的一个函数,它根据值创建可观察对象。资料来源:https://rxjs.dev/api/index/function/of