【问题标题】:How to mock a method that is returning a subscribe如何模拟返回订阅的方法
【发布时间】:2021-04-19 04:59:48
【问题描述】:

我目前有一个我想测试和模拟的方法,但不知道该怎么做

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:无法读取未定义的属性“订阅”]。有人可以建议我缺少什么吗?

【问题讨论】:

  • 如果您包含您的测试文件,它会更容易提供帮助。
  • 谢谢。刚刚更新。虽然运行 onMount 方法只是一个快照

标签: reactjs typescript rxjs jestjs enzyme


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2019-10-26
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多