Use promise to delay mocha

644 Views Asked by At

I'm using mocha and zombie.
My goal is to load data from website <a> tags from website then query name and href. So far this is working:

const Browser = require('zombie')

const browser = new Browser()

browser.visit('page', () => {
  let temp = browser.document.querySelectorAll('a selector')
  for (let i = 0; i < temp.length; i++) {
      browsers.push({ name: temp[i].innerHTML, url: temp[i].href })
  }
  delete temp
})

My next step would be using this data in testing.

const data = [{ name: 'name', url: 'test' }]
describe('test with for', () => {
    for (let i = 0; i < data.length; i++) {
        it(data[i].name, () => {
            // test code with url of data[i]
        })
    }
})

The only problem I have is that data array is filled asynchronously and it has to be present at time of invoking it function.

I tryed using before but i saw that it does not make sence here (because of invoking async function don't stop code to execute and only function pased in it can depend on async data) So I tryed to do this using Promise but it also failed.

const data = []
new Promise((resolve, reject) => {
    // filing data
    resolve()
}).then(() => {
    describe('...', () => {
        for (let i = 0; i < data.length; i++) {
          it (data[i].name, () => {})
        }
    })
})

I looked at mocha documentation and didn't find solution :/
How should I solve this problem?

1

There are 1 best solutions below

0
Maciej Kozieja On BEST ANSWER

Ok i found solution, problem was my mistake i forgot to remove describe inwith my browser reading was contained that's why --delay did not work.

Running code:

const { describe, it } = require('mocha')
const { assert, expect } = chai = require('chai')
const Browser = require('zombie')

const browser = new Browser()
const browsers = []

new Promise((resolve, reject) => {
    browser.visit('site', () => {
        let temp = browser.document.querySelectorAll('selector')
        for (let i = 0; i < temp.length; i++) {
            browsers.push({ name: temp[i].innerHTML, url: temp[i].href })
        }
        delete temp
        resolve()
    })
}).then(() => {
    describe('Get browser name', () => {
        for (let i = 0; i < browsers.length; i++) {
          it(browsers[i].name, () => {

          })
        }
    })
    run()
})