reactjs - 我的模拟函数在 Sagas 测试中没有被调用

标签 reactjs react-native testing jestjs saga

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

这就是我的传奇:

export async function loginApi(user) {
  return await api.post('/auth/customers/login', {
    email: user.email, //<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98fbedebecf7f5fdeaa9d8f5f1b6f5fd" rel="noreferrer noopener nofollow">[email protected]</a>
    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();
     |                      ^

最佳答案

runSaga 返回一个 Task 对象,而不是 Promise,因此您需要调用 toPromise

const result = await runSaga(
  {
    dispatch: action => dispatched.push(action),
  },
  loginActionEffect,
).toPromise();
PS。您测试传奇的方式与推荐的方式不符。请阅读此docs 。正如我在评论中所写的。声明性效果的一件很酷的事情是效果执行依赖于解释器。因此,您不需要在测试中实际执行或模拟任何内容。

关于reactjs - 我的模拟函数在 Sagas 测试中没有被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59755276/

相关文章:

javascript - React shouldComponentUpdate 太多递归

reactjs - React Native webview cookie问题

python - 在测试序列中的测试之间保存数据的模式

testing - 具有多个断言和报告的 Clojure 测试

testing - 在concolic测试中, "concrete execution"是什么意思?

reactjs - React 路由器热重载不起作用

javascript - 如何在 componentWillReceiveProps 中触发页面重定向?

使用 antd ReactJs AutoComplete 未显示在下拉列表中

react-native - 在没有调试的情况下启动时 react native 错误

javascript - 开发服务器返回响应错误码: 500 react-native