【问题标题】:Perform API calls to WS in jest tests在开玩笑测试中对 WS 执行 API 调用
【发布时间】:2018-03-05 20:55:33
【问题描述】:

是否可以在开玩笑测试中执行 api 调用?我不想模拟数据,我想执行一个具体的 api 请求。我正在使用 superagent/axios,但在开玩笑测试中运行时它总是失败。

这是测试文件

import * as request from 'superagent';
test('Expected undefined', () => {
    console.log('START');
    expect.assertions(1);
    request.get('http://httpbin.org/ip')
        .then(data => {
            console.log('Response -> ',JSON.stringify(data));
            expect(true).toBeTruthy();
        })
        .catch(err => {
            console.log('Error -> ', err);
            expect(true).toBeTruthy();
        });
    console.log('END');
});

这是错误

Expected undefined

    expect.assertions(1)

    Expected one assertion to be called but received zero assertion calls.

      at extractExpectedAssertionsErrors (node_modules/expect/build/extract_expected_assertions_errors.js:46:19)

在控制台中

START
END

问候

【问题讨论】:

  • 添加您的代码,也许有人可以提供帮助
  • 是的,您可以在 jest 函数中执行 api 请求。告诉我们你的代码,我猜还有其他问题
  • 添加代码,是普通的http请求。如果将相同的代码放在一个新文件中(没有 'test' 包装器)并使用 node 命令启动它,它工作得很好。

标签: node.js reactjs jestjs


【解决方案1】:

嘿@Premier,您需要使测试异步,因为请求是一个承诺。有几种方法可以告诉 jest 等待您的请求完成。看看测试异步函数的笑话文档:https://facebook.github.io/jest/docs/en/tutorial-async.html

async/await:

test('Expected undefined', async () => {
  console.log('START');
  expect.assertions(1);
  await request.get('http://httpbin.org/ip')
    .then(data => {
      console.log('Response -> ',JSON.stringify(data));
      expect(true).toBeTruthy();
    })
    .catch(err => {
      console.log('Error -> ', err);
      expect(true).toBeTruthy();
    });
  console.log('END');
});

兑现承诺

test('Expected undefined', () => {
  console.log('START');
  expect.assertions(1);
  return request.get('http://httpbin.org/ip')
    .then(data => {
      console.log('Response -> ',JSON.stringify(data));
      expect(true).toBeTruthy();
    })
    .catch(err => {
      console.log('Error -> ', err);
      expect(true).toBeTruthy();
    });
});

使用done回调

test('Expected undefined', (done) => {
  console.log('START');
  expect.assertions(1);
  request.get('http://httpbin.org/ip')
    .then(data => {
      console.log('Response -> ',JSON.stringify(data));
      expect(true).toBeTruthy();
      done();
    })
    .catch(err => {
      console.log('Error -> ', err);
      expect(true).toBeTruthy();
      done(err);
    });
  console.log('END');
});

【讨论】:

  • 是的,谢谢,我忘记了退货声明。它有效
  • 你的异步代码不需要使用嵌套的 Promise。您可以只使用var data = await request.get(...),也可以使用普通的try { ... } catch (err) { ... } 块来捕获promise 拒绝。
猜你喜欢
  • 2020-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-21
  • 1970-01-01
  • 2020-02-06
  • 2020-03-25
相关资源
最近更新 更多