【问题标题】:beforeEach fetch() - pass res to 'it' functionbeforeEach fetch() - 将 res 传递给 'it' 函数
【发布时间】:2020-03-17 04:10:42
【问题描述】:

在 mocha/chai TDD 测试中这个 API 调用真的很吃力,我正在尝试设置。

基本上,beforeEach() 测试,我想进行 fetch 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(),并成功地将 for 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.logging:

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

【问题讨论】:

    标签: javascript api promise mocha.js chai


    【解决方案1】:

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

    describe('foo', () => {
      let result;
    
      beforEach(async () => {
        result = await blah();
      });
    
      test('bar', () => {
        assert.equal(result, 'foobar');
      });
    });
    

    这实际上与 mocha 或测试框架没有任何关系,它只是一个惯用的模式,你会在 js 中看到,无论是 mocha、jest 等测试。

    【讨论】:

      【解决方案2】:

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

      希望对你有帮助!

      【讨论】:

        猜你喜欢
        • 2016-02-12
        • 1970-01-01
        • 1970-01-01
        • 2018-02-15
        • 2021-12-27
        • 1970-01-01
        • 2014-05-04
        • 1970-01-01
        • 2017-10-19
        相关资源
        最近更新 更多