简体   繁体   中英

beforeEach fetch() - pass res to 'it' function

Really struggling with this API call in a mocha/chai TDD test, I'm trying to setup.

Basically, beforeEach() test, I want to make a fetch api call. And then pass my res into each it() function, so I can run individual tests on the response.

My beforeEach() function seems to work, as I can console.log(res) successfully.

However, I get the following error when my it() function/test runs:

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

If I add done() into my beforeEach function, this doesn't fix the problem though. I then get a new error, which I can't seem to resolve:

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

I'm getting lost on how to resolve this issue. How can I successfully run my beforeEach() , and pass for res into each subsequent it() function successfully?

Here's my code:

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);
})

And here is what is console.logging in my beforeEach() :

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 } }

Typically for an async beforeEach function you need to instantiate the variable before the hook, then in the hook definition override the variable.

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

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

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

This doesn't really have anything to do with mocha or the test framework, it's just an idiomatic pattern you'll see with testing in js be it with mocha, jest, etc.

in beforeEach , we should choose to stick either with async/await or promise . Don't mix them because it's unnecessary.

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);    
  });
});

Alternatively, for 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);    
  });
});

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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