I'm looking for a solution to define Mocha tests after getting data asynchronously.
For now, I use gulp-webdriver to getting HTML content with Selenium. And I want tests certain HTML tags structure.
For example, I want to get all buttons structure from an HTML page.
1° In Mocha Before(), I get buttons :
var buttons = browser.url("url").getHTML("button");
2° And after that, I want tests each button in a separate it
:
buttons.forEach(function(button) { it() });
The only solution found is loading HTML and extract buttons with Gulp before launch Mocha test with data_driven or leche.withData plugin.
Do you know another solution directly in Mocha test definition?
Thanks in advance,
Mocha supports two ways to handle asynchronicity in tests. One way is using the done callback. Mocha will try to pass a function into all of your
it
s,before
s, etc. If you accept thedone
callback, it's your responsibility to invoke it when your asynchronous operation has completed. Callback style:The other approach is to use Promises. Since your call to getHTML returns a Promise, you could just return that promise and Mocha would know to wait for the promise to settle before moving ahead with anything.
Here is an example of the Promise style:
A couple things worth noting about this: -
getHtml()
returns a promise for the html buttons. Whenever the asynchronous call togetHTML
completes, the function passed into thethen
function gets invoked and the resulting value from the call togetHTML
is passed in. - Returning that promise in the before lets mocha know that you're doing something asynchronous. Mocha will wait for that promise to settle before moving past your 'before'.For your specific example, you might want to try is something like this:
You can actually create dynamic
It()
tests with mocha if you don't mind abusing thebefore()
hook a bit:It doesn't seem possible to dynamically create it() tests with mocha.
I finally organise my test like this :