【问题标题】:My mock function isn't being called in Sagas test在 Sagas 测试中没有调用我的模拟函数
【发布时间】:2020-05-02 10:45:15
【问题描述】:

我正在尝试用 Jest 测试 Sagas,但我无法让 Sagas 调用 loginApi 模拟函数,似乎它正在调用实际函数。有人可以帮我解决这个问题吗?

这就是我的传奇:

export async function loginApi(user) {
  return await api.post('/auth/customers/login', {
    email: user.email, //customer1@mi.me
    password: user.password, //12345678
  });
}

// Saga function that handles the side effect when the loginWatcher is triggered
export function* loginActionEffect(loginAction) {
  //console.tron.log('login Action Effect');

  try {
    const response = yield call(loginApi, loginAction.user);
    // console.log('response:' + response);

    yield AsyncStorage.setItem('access_token', response.data.access_token);
    yield put(LoginActions.setLogin(loginAction.user));
    yield put(LoginActions.setError(''));
  } catch (e) {
    //console.log('problema com o login!');
    yield put(LoginActions.setError('Email ou senha incorretos!'));
  }
}

这是我的测试:

it('should receive token in case of success', async () => {
    const mockToken = {token: 'kaajfalkfjlaniurvayeg'};
    const loginApi = jest.fn().mockImplementation(() => Promise.resolve(mockToken));
    const dispatched = [];

    const result = await runSaga(
      {
        dispatch: action => dispatched.push(action),
      },
      loginActionEffect,
    );

    expect(loginApi).toHaveBeenCalled();
    expect(dispatched).toContainEqual(Creators.setLogin());
    expect(dispatched).toContainEqual(Creators.setError());
    loginApi.mockClear();
  });

这是我的测试结果:

expect(jest.fn()).toHaveBeenCalled()

Expected number of calls: >= 1
Received number of calls:    0

  21 |     );
  22 | 
> 23 |     expect(loginApi).toHaveBeenCalled();
     |                      ^

【问题讨论】:

  • 嗯,但你为什么要这样测试你的传奇?声明式效果很酷的一点是,您可以使用简单的相等检查来测试它们,而无需执行任何实际效果和模拟操作。
  • 我建议您查看有关如何测试 sagas 的文档。

标签: reactjs react-native testing jestjs saga


【解决方案1】:

runSaga 返回一个Task 对象而不是Promise 所以你需要调用toPromise

const result = await runSaga(
  {
    dispatch: action => dispatched.push(action),
  },
  loginActionEffect,
).toPromise();

PS。您测试 sagas 的方式与推荐的不符。请阅读此docs。正如我在评论中所写。声明式效果的一件很酷的事情是效果执行依赖于解释器。因此,您无需在测试中实际执行或模拟任何内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2021-03-30
    • 2017-11-17
    相关资源
    最近更新 更多