I'm accustomed to writing Mocha tests using the standard NodeJs assert library like this:
describe('Some module', () => {
var result = someCall();
it('Should <something>', () => {
assert.ok(...);
});
})
but now my call returns a promise... so I want to write:
describe('Some module', async () => {
var result = await someCall();
it('Should <something>', () => {
assert.ok(...);
});
})
but it doesn't work. My tests don't run at all. Curiously,
describe('Some module', async () => {
it('Should <something>', () => {
var result = await someCall();
assert.ok(...);
});
})
works fine but the problem is that I want to make a single call and run many tests against it, so I want to make the call outside the it() calls
How do I make it work?
and please don't recommend Chai. I want to use the standard assert library
To test asynchronous code, we use the XCTestExpectation class and wait for the expected outcome. The workflow is to create an expectation, and then when the asynchronous task completes successfully, we fulfil that expectation. We will wait for a specific amount of time for the expectation to be fulfilled.
Use of Test.startTest() and Test. stopTest() . The system collects all asynchronous calls made after startTest() . When stopTest() is executed, these collected asynchronous processes are then run synchronously and complete before control returns to our code.
before
accepts an async
function so you can get the result
before your tests run and use it in your tests like this:
const assert = require('assert');
const someCall = () => Promise.resolve('hi');
describe('Some module', () => {
let result;
before(async () => {
result = await someCall();
});
it('Should <something>', () => {
assert.equal(result, 'hi'); // Success!
});
});
Although a little unconventional in use, one approach might be to use the before()
hook to achieve what you require.
The before()
hook would provide a means of calling functionality (ie someCall()
) prior to the rest of the tests in your suite. The hook itself supports execution of asynchronous functionality via a callback function (ie done
) that can be called once asynchronous functionality has completed:
before((done) => {
asyncCall().then(() => {
/* Signal to the framework that async call has completed */
done();
});
});
One way to integrate this with your existing code might be as follows:
describe("Some module", () => {
/* Stores result of async call for subsequent verification in tests */
var result;
/* User before hook to run someCall() once for this suite, and
call done() when async call has completed */
before((done) => {
someCall().then((resolvedValue) => {
result = resolvedValue;
done();
});
});
it("Should <something>", () => {
/* result variable now has resolved value ready for verification */
console.log(result);
});
});
Hope that helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With