繁体   English   中英

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

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

我正在用Enzyme和Jest测试React Native组件。 我已经能够测试是否调用了mocked函数(在本例中为Alert.alert),如下所示:

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

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

这种方法运作良好。

无论如何,我有一个Login按钮,它会启动一个提取。 我的获取功能是这样的:

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中为服务调用编写了一些测试(我确实使用了你没有的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(我当时做过),上面的链接会为您提供如何安装其他承诺的说明。

现在你有没有放东西的事件队列的末尾承诺,您可以改为调用接下来then通过调用mp.tick() 在你的情况下,这将是一些东西

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

另一种方式, 在开玩笑中开箱即用附加另一个then expects返回整个承诺。 你可以在这里找到详细信息: 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)并为此编写测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM