heyooo12
heyooo12

Reputation: 149

Testing multiple promises with mocha?

I am testing promises which I get from the request-image-size library. Upon request from the library with an image URL I receive as a response of the image dimensions and an error if the image can`t be opened.

My test.js file, It case:

describe('Test images', () => {
  it('Should test all image sizes',async (done) => {

   const imagesResonses = await getAllImageResponses(imagesURLs)

      // if I console log imageResponses I get an array of promises, 
      // two of them must be rejected and throw an error
      // [
      //   Promise { <pending> },
      //   Promise { <pending> },
      //   Promise { <pending> },
      //   Promise { <pending> },
      //   Promise { <pending> },
      //   Promise { <pending> }
      // ]
      imagesResonses.map((image) => image.then((res) => {
        console.log(res)
        assert(res.height > 0, 'height must be greater than zero');
        done()
      }).catch((err) => {
        console.log(err)
        done(err)
      }))
  })

})

Test results: enter image description here

The problem:

I have successfully tested single promises before in mocha with using done(), but never multiple promises. I know I am not handling the promises the right way, but just dont know what else to try.

In this case, the tests are run 2 times and at the end I receive an error:

     done() called multiple times in test <Test links and images S
hould test all image sizes> of file C:path/test.js; in addition, don
e() received error: Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both.

Expectation: I want to run the test on each promise and do an assertion, and if the promise is rejected log out the error.

Upvotes: 0

Views: 159

Answers (1)

fgkolf
fgkolf

Reputation: 1065

You can use a for..of loop along with await in order to execute your promises and make your assertions sequentially.

Haven't tested this but it should work:

for (const image of imagesResonses) {
  try {
    const res = await image
    assert(res.height > 0, 'height must be greater than zero');
  } catch(err) {
    console.log(err)
  }   
}

Also you can read more in this answer along with it's very interesting comments about why you can't achieve this using a forEach/map.

Upvotes: 1

Related Questions