如何在异步函数中测试jest.fn().mock.calls

How to test jest.fn().mock.calls in asynchronous function

我正在使用 Enzyme 和 Jest 测试 React Native 组件。我已经能够测试是否调用了模拟函数(在这种情况下为Alert.alert),如下所示:

Alert.alert = jest.fn();
someButton.simulate('Press');

expect(Alert.alert.mock.calls.length).toBe(1);

这种方法效果很好。

无论如何,我有一个登录按钮,它启动一个获取。我的 fetch 函数是这样的:

fetch(ipAddress, {
           ...
        })
            .then(response => response.json())
            .then((responseJson) => {
                if (responseJson.login === 'success') {
                    Alert.alert('Login', 'Logged in succesfully!');
                    console.log('i'm here');

我用承诺嘲笑了一次获取。我将控制台打印添加到我的 fetch 函数中,并注意到它们打印在测试用例中,正如我预期的那样。这意味着当测试为 运行.

时打印 '我在这里'

无论如何,当我在测试用例中模拟登录按钮按下时,Alert.alert.mock.calls.length 为零。我在这里做错了什么?

我没有用 React Native 检查这个,但我确实在 React 中为服务调用写了一些测试(我确实使用了你没有使用的 Flux - 但没关系,在不同的地方它是相同的原理) .本质上,当您执行 expect 时,承诺链尚未完成。这意味着,Alertconsole.log 都在 expect 之后执行,因为默认的 promise 实现将所有后续步骤放在事件队列。

克服此问题的一种方法是使用 https://www.npmjs.com/package/mock-promises - 您的规范中的 beforeEach 方法需要调用 install,如下所示:

beforeEach(() => {
  Q=require('q');
  mp=require('mock-promises');
  mp.install(Q.makePromise);
  mp.reset();
  // more init code
});

别忘了

afterEach(() => {
  mp.uninstall();
});

如果您不使用 Q(我当时使用),上面 link 为您提供了如何安装其他 promise 的说明。

现在您可以承诺不会将事情放在事件队列的末尾,您可以改为通过调用 mp.tick() 来调用下一个 then。在你的情况下,这将是

it("...", () => {
  Alert.alert = jest.fn();
  someButton.simulate('Press');
  mp.tick();
  mp.tick(); // then and then
  expect(Alert.alert.mock.calls.length).toBe(1);
});

另一种方式,开箱即用 是附加另一个 thenexpects 返回 整个承诺。您可以在此处找到详细信息:https://facebook.github.io/jest/docs/en/tutorial-async.html

基本上,它应该是这样的:

functionReturningPromise = () => {
  // do something
  return thePromise;
}

// now testing it
it("...", () => {
  return /* !!! */ functionReturningPromise().then(() => {
    expect(/*something*/).toBeSth();
  });
});

但是,在您的情况下,这会很困难,因为您无法在测试代码中处理 promise。但是,您可以将所有获取逻辑拆分成一个专用方法(returns 承诺至少用于测试)并为此编写测试。