beforeEach fetch()-将res传递给'it'函数

时间:2019-11-21 09:23:50

标签: javascript api promise mocha chai

在mocha / chai TDD测试中,确实很难解决此API调用,我正在尝试设置。

基本上,beforeEach()测试中,我想进行访存api调用。然后将我的res传递到每个it()函数中,这样我就可以对响应运行单独的测试。

我的beforeEach()函数似乎可以正常运行,因为我可以成功地console.log(res)。

但是,我的it()函数/测试运行时出现以下错误:

  

错误:超时超过2000毫秒。对于异步测试和挂钩,请确保调用了“ done()”;如果返回了Promise,请确保它可以解决。

如果我将done()添加到我的beforeEach函数中,则无法解决问题。然后,我收到一个新错误,似乎无法解决:

 Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both.

我不知道如何解决此问题。如何成功运行我的beforeEach(),并成功将res传递给每个后续的it()函数?

这是我的代码:

describe('1) Check for succcessful fetech API call', () => {
beforeEach( async (done) => {
   await fetch('https://pixabay.com/api/?key=9656065-a4094594c34f9ac14c7fc4c39&q=manhattan&image_type=photo&page=1&per_page=9')
    .then((res) => {
        console.log(res);
        return res.json();
    })
    done();
});

it('a) Should return an object, with an array count of 9 elements', function(res) {
        console.log(res);
        // expect(res).to.be.an('object');
        // expect(res.hits).to.have.lengthOf(9);
})

这是在我的beforeEach()中登录console。

Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]: 
   { body: 
      Gunzip {
        _readableState: [ReadableState],
        readable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 7,
        _maxListeners: undefined,
        _writableState: [WritableState],
        writable: true,
        allowHalfOpen: true,
        _transformState: [Object],
        bytesRead: 0,
        _handle: [Zlib],
        _hadError: false,
        _writeState: [Uint32Array],
        _outBuffer: <Buffer 7b 22 74 6f 74 61 6c 48 69 74 73 22 3a 35 30 30 2c 22 68 69 74 73 22 3a 5b 7b 22 6c 61 72 67 65 49 6d 61 67 65 55 52 4c 22 3a 22 68 74 74 70 73 3a 2f ... >,
        _outOffset: 0,
        _level: -1,
        _strategy: 0,
        _chunkSize: 16384,
        _flushFlag: 2,
        _scheduledFlushFlag: 0,
        _origFlushFlag: 2,
        _finishFlushFlag: 2,
        _info: undefined },
     disturbed: false,
     error: null },
  [Symbol(Response internals)]: 
   { url: 'https://pixabay.com/api/?key=9656065-a4094594c34f9ac14c7fc4c39&q=manhattan&image_type=photo&page=1&per_page=9',
     status: 200,
     statusText: 'OK',
     headers: Headers { [Symbol(map)]: [Object] },
     counter: 0 } }

2 个答案:

答案 0 :(得分:0)

通常对于异步beforeEach函数,您需要在钩子之前实例化该变量,然后在钩子定义中覆盖该变量。

describe('foo', () => {
  let result;

  beforEach(async () => {
    result = await blah();
  });

  test('bar', () => {
    assert.equal(result, 'foobar');
  });
});

这实际上与mocha或测试框架没有任何关系,这只是在js中进行测试的惯用模式,无论是与mocha,jest等。

答案 1 :(得分:0)

beforeEach中,我们应该选择保留async/awaitpromise。不要混合它们,因为这是不必要的。

async/await

describe("1) Check for succcessful fetech API call", () => {
  let res; // define variable to store the response

  beforeEach(async () => { // define async
    const response = await fetch(
      "https://pixabay.com/api/?key=9656065-a4094594c34f9ac14c7fc4c39&q=manhattan&image_type=photo&page=1&per_page=9"
    );
    res = response.json(); // store the response to our variable
  });

  it("a) Should return an object, with an array count of 9 elements", function(res) {
    console.log(res);    
  });
});

或者,对于promise

describe("1) Check for succcessful fetech API call", () => {
  let res; // define variable to store the response

  beforeEach((done) => { // specify done
    fetch(
      "https://pixabay.com/api/?key=9656065-a4094594c34f9ac14c7fc4c39&q=manhattan&image_type=photo&page=1&per_page=9"
    ).then((response) => {      
      res = response.json(); // store the response to our variable
      done(); // call done here once promise is resolved
    })    
  });

  it("a) Should return an object, with an array count of 9 elements", function(res) {
    console.log(res);    
  });
});

希望有帮助!