代码之家  ›  专栏  ›  技术社区  ›  BrunoLM

如何使用API调用测试传奇?

  •  1
  • BrunoLM  · 技术社区  · 8 年前

    我有一个传奇故事

    export function* mysaga(api, action) {
      const response = yield call(api.service, action);
      yield put(NavActions.goTo('Page', { success: response.ok }));
    }
    

    调用API并使用返回值导航到另一个屏幕,传递API调用结果( response.ok

    it('test', () => {
      // ...
    
      const gen = mysaga(api, action);
      const step = () => gen.next().value;
    
      // doesn't actually run the api
      const response = call(api.service, {});
    
      expect(step()).toMatchObject(response); // ok
    
      // error, Cannot read property 'ok' of undefined
      expect(step()).toMatchObject(
        put(NavActions.goTo('Page', { success: response.ok }))
      );
    });
    

    response 没有定义。

    1 回复  |  直到 8 年前
        1
  •  6
  •   Martin Kadlec    8 年前

    默认情况下,yield表达式解析为它生成的任何内容。但是,您可以将另一个值传递给gen.next方法,然后将收益率表达式解析为您在那里传递的值。

    const gen = rootSaga(api, action);
    const step = (val) => gen.next(val).value;
    
    const mockResponse = { ok: true };
    const response = call(api.service, {});
    
    expect(step(mockResponse)).toMatchObject(response); // ok
    
    expect(step()).toMatchObject(
      put(NavActions.goTo('Page', { success: true }))
    );