在jest测试中对WS执行API调用

时间:2018-03-05 20:55:34

标签: node.js reactjs jest

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

这是测试文件

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

此致

1 个答案:

答案 0 :(得分:1)

嘿@Premier你需要让你的测试异步,因为请求是一个承诺。有几种方法可以让jest等待你的请求完成。查看用于测试异步函数的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');
});