How to run async functions in before hook in MochaJS? - node.js

I try to call a lot of async functions in my mocha JS before hook but they are executed at last. Basically I am trying to execute repeated tests with different params from the constructor initialization.
I tried with only one function but it also execute at last.Tried to pass done() function to inner async function but it doesnt help either.
a.test.js and base.tests.js files :
describe('Test block', () => {
before((done) => {
const baseClass = new baseClass()
baseTests.applyTests(done)
});
describe('test',()=>{
....first which should be executed;
})
}
----------------------------------------------------------------
class baseClass {
constructor() {
init smth....
}
async applyTests(done) {
await Promise.All(
[
a(),
b(),
c()
]
done();
)
}
async a() {
return describe('TEST', () => {
it('TEST', (done) => {
chai.request(server)
.get(url)
.end((err, res) => {
asserts...
done();
});
});
}}
I expect to run first the async operations in the before hook and after that all other tests.

Keep in mind that describe and it blocks do not execute any tests; they add tests to the test list that Mocha will execute. Putting a describe block inside a function called from a before hook like this won't ever end up executing code like chai.request(... etc. (And even if it did, it would be totally broken: a before hook is run before each test, you don't want to do asserts there because it won't be linked to any particular unit test.)
I can't give more concrete advice because I'm not sure what you were trying to accomplish, but in general, your describe and it blocks should be top-level constructs and not put inside other code like this.
EDIT: Just to make the execution path here clear: your before hook runs, which calls applyTests, which calls a(), which executes a describe block and adds your unit test TEST to the test list, then it returns. It then begins running tests, including test and TEST.
EDIT: Ah, makes sense, let me suggest two patterns that are often used in unit tests.
Pattern 1: "Test Loop"
This pattern creates many similar-looking tests, using an array of input params to produce appropriate test descriptions and test bodies.
[
{ foo: "milk", bar: "smoothie" },
{ foo: "yogurt", bar: "fridge" },
{ foo: "whatever", bar: "container" }
].forEach(test => {
it("puts the " + test.foo + " in the " + test.bar, function () {
assert(subject.someMethod(foo) === bar);
});
});
Pattern 2: "Test Helper"
This pattern creates individual tests, but puts a common test body in a helper method so it can be reused.
function testSomeMethod(foo, bar) {
assert(subject(foo) == "bar");
}
it("puts the milk in the fridge", function () {
testSomeMethod("milk", "fridge");
});
it("puts the cereal in the pantry", function () {
testSomeMethod("cereal", "pantry");
});
Examples above are very simple, but either the test loop or the test helper pattern can be used to encapsulate a much more complicated series of steps (set up a request, look at some response headers / bodies, etc.).

Related

How to do callback in our component using react jest test cases

How can we do callback on success and failue cases for below lines of code for test coverage using jest
const handleService = () => {
window.domain.service("1321",'',onSuccess, onFailure)
}
const onSuccess = () => {
....update state values
}
const onFailure = () => {
....update state values
}
Something like this:
Spy on window.domain.service to gain access to the calls it receives. This will allow you to access the parameters of those calls which will be "1321",'',onSuccess, onFailure
Assign the function you wish to test to a variable
Invoke the function to execute the code in it (this will get you the coverage)
(Optional) assert that the callback functions behave correctly
Here is a snippet to help demonstrate
it('should run', () => {
// Some setup to create the function on the window, may not be needed if done elsewhere.
// Could be good to do this in a beforeEach and clean up in afterEach to avoid contaminating the window object
window.domain = {
service: () => {},
}
// Spy on the window.domain.service method.
// Provide a mock implementation if you don't want the real one to be called
const serviceSpy = jest.spyOn(window.domain, 'service');
executeYourCode();
// capture the arguments to the call
const [_arg1, _arg2, onSuccess, onFailure] = serviceSpy.mock.calls[0];
// execute the callbacks
onSuccess();
onFailure();
});

Can Jest's beforeAll wait until its describe scope to execute?

I've been baffled for the last few days by how Jest deals with beforeAll inside describe blocks. I want each describe's beforeAll to only execute when it's time to run the tests inside that describe.
I've written this test file (test test file?):
async function wait1sec() {
return new Promise(resolve => setTimeout(resolve, 1000));
}
async function logWait(i, isDescribe = false) {
console.log(`before wait inside ${ isDescribe ? 'describe' : 'it' } #` + i);
await wait1sec();
console.log(`after wait inside ${ isDescribe ? 'describe' : 'it' } #` + i);
expect(true).toEqual(true);
}
function logSync(i, isBefore = false) {
console.log(`synchronous function ${ isBefore ? 'before' : 'it' } #${ i }`);
}
describe('async behavior', () => {
describe('block 1', () => {
const i = 1;
beforeAll(() => logSync(i, true));
it('sync test in block 1', () => logSync(i));
});
describe('block 2', () => {
const i = 2;
beforeAll(() => logSync(i, true));
it('sync test in block 1', () => logSync(i));
});
});
You can see the remnants of the fact that I was testing this in the context of async behavior but it turns out that it's confusing even without async.
What I hope get is:
synchronous function before #1
synchronous function it #1
synchronous function before #2
synchronous function it #2
What I actually get is
synchronous function before #1
synchronous function before #2
synchronous function it #1
synchronous function it #2
What's even worse is that if I skip the second block (with xdescribe), the second beforeAll still runs!
So I guess it's not that confusing, I guess it's just pretty clear how it works, it's just not the way I want it to work.
Is there any way, short of simply putting my "beforeAll" code inside my first test of the block, to get the result I want?
Note: For a bit of context, I'm using these tests to interact with an external REST API to test how I've set up a workflow. In other words, I'm not testing my own code, and all the interactions with the server are real and result in real CRUD transactions. They're not significant, and they're easy to clean up, so it's a safe and controlled thing to be doing. And my tests build on each other, from one describe to the next (i.e., the page I'm working with is created once, before the very first test, and modified with the REST API throughout the remainder) which means that a beforeAll in describe #2 running before the tests in describe #1 can mess up the whole thing. (Especially if I'm trying to skip blocks with xdescribe!)
You can use -i flag for run your test sequentially;
Also You can wrap your describe blocks into IIFE (or add function for that):
describe('async behavior', () => {
(() =>
describe('block 1', () => {
...
}))();
(() =>
describe('block 2', () => {
...
}))();
});
and it will work as You expect, but I'm not sure is it a good practice. Maybe this way will create some other logical errors for some other async behaviour;

Mocha unit testing: where to create variables

I'm just getting into unit testing for the first time. Using Mocha in Node as the testing framework. All the examples I've come across create variables inside the it(). Does it matter if they are created inside or outside of it()? For example, if I have multiple it()s inside a describe(), and I need the same mocked data across all of the it()s. I'd rather not re-create the same variable repeatedly, if possible.
describe ('MyClass', function () {
let myObj = new MyObj // Mock data here
it ('Should be...', function () {
....
})
it ('Should be...', function () {
....
})
...
})
It's totally acceptable to have variables live outside of your individual it blocks, but it may not be appropriate depending on your use case.
For objects that you do not expect to change, Object.freeze is an option: const myObj = Object.freeze(new MyObj).
If you expect your tests to change your object, you should use beforeEach to ensure that they are restored to the proper state; this will prevent your it blocks from polluting one another and avoid an unpleasant debugging journey.
For example:
describe('MyClass', function () {
let myObj
beforEach(() => {
myObj = new MyObj()
})
it('changes myObj', () => {
changeProp(myObj.sum)
expect(myObj.sum).toEqual(4)
})
it('depends on myObj being the same', () => {
expect(myObj.sum).toEqual(2)
})
})
Alternately, you can eschew the fat arrow syntax and rely on the shared context between blocks in mocha:
beforeEach(function () {
this.myObj = new MyObj()
})
it('changes myObj', function () {
addTwo(this.myObj.sum)
expect(this.myObj.sum).toEqual(4)
})
it('depends on myObj being the same', function () {
expect(this.myObj.sum).toEqual(2)
})

How can I build my test suite asynchronously?

I'm trying to create mocha tests for my controllers using a config that has to be loaded async. Below is my code. However, when the mocha test is run, it doesn't run any tests, displaying 0 passing. The console.logs are never even called. I tried doing before(next => config.build().then(next)) inside of the describe, but even though the tests run, before is never called. Is there a way to have the config be loaded one time before any tests are run?
'use strict';
const common = require('./common');
const config = require('../config');
config
.build()
.then(test);
function test() {
console.log(1);
describe('Unit Testing', () => {
console.log(2);
require('./auth');
});
}
You should run Mocha with the --delay option, and then use run() once you are done building your test suite. Here is an example derived from the code you show in the question:
'use strict';
function test() {
console.log(1);
describe('Unit Testing', () => {
console.log(2);
it("test", () => {
console.log(3);
});
});
// You must use --delay for `run()` to be available to you.
run();
}
setTimeout(test, 1000);
I'm using setTimeout to simulate an asynchronous operation. Using --delay and run() allows you to build a suite that is the result of an asynchronous computation. Note, however, that the suite must be built in one shot. (You cannot have an asynchronous process inside describe that will make calls to it. This won't work.)
One thing you should definitely not do is what rob3c suggests: calling describe or it (or both) from inside a hook. This is a mistake that every now and then people make so it is worth addressing in details. The problem is that it is just not supported by Mocha, and therefore there are no established semantics associated with calling describe or it from inside a hook. Oh, it is possible to write simple examples that work as one might expect but:
When the suite becomes more complex, the suite's behavior no longer corresponds to anything sensible.
Since there are no semantics associated with this approach, newer Mocha releases may handle the erroneous usage differently and break your suite.
Consider this simple example:
const assert = require("assert");
const p = Promise.resolve(["foo", "bar", "baz"]);
describe("top", () => {
let flag;
before(() => {
flag = true;
return p.then((names) => {
describe("embedded", () => {
for (const name of names) {
it(name, () => {
assert(flag);
});
}
});
});
});
after(() => {
flag = false;
});
it("regular test", () => {
assert(flag);
});
});
When we run it, we get:
top
✓ regular test
embedded
1) foo
2) bar
3) baz
1 passing (32ms)
3 failing
// [stack traces omitted for brevity]
What's going on here? Shouldn't all the tests pass? We set flag to true in the before hook for the top describe. All tests we create in it should see flag as true, no? The clue is in the output above: when we create tests inside a hook, Mocha will put the tests somewhere but it may not be in a location that reflects the structure of the describe blocks in the code. What happens in this case is that Mocha just appends the tests created in the hook the the very end of the suite, outside the top describe, so the after hook runs before the dynamically created tests, and we get a counter-intuitive result.
Using --delay and run(), we can write a suite that behaves in a way concordant with intuition:
const assert = require("assert");
const p = Promise.resolve(["foo", "bar", "baz"]).then((names) => {
describe("top", () => {
let flag;
before(() => {
flag = true;
});
after(() => {
flag = false;
});
describe("embedded", () => {
for (const name of names) {
it(name, () => {
assert(flag);
});
}
});
it("regular test", () => {
assert(flag);
});
});
run();
});
Output:
top
✓ regular test
embedded
✓ foo
✓ bar
✓ baz
4 passing (19ms)
In modern environments, you can use top-level await to fetch your data up front. This is a documented approach for mocha: https://mochajs.org/#dynamically-generating-tests
Slightly adapting the example from the mocha docs to show the general idea:
function fetchData() {
return new Promise((resolve) => setTimeout(resolve, 5000, [1, 2, 3]));
}
// top-level await: Node >= v14.8.0 with ESM test file
const data = await fetchData();
describe("dynamic tests", function () {
data.forEach((value) => {
it(`can use async data: ${value}`, function () {
// do something with data here
});
});
});
This is nice as it is on a per-file basis, and doesn't involve you taking on management responsibility of the test runner as you do with --delay.
The problem with using the --delay command line flag and run() callback that #Louis mentioned in his accepted answer, is that run() is a single global hook that delays the root test suite. Therefore, you have to build them all at once (as he mentioned), which can make organizing tests a hassle (to say the least).
However, I prefer to avoid magic flags whenever possible, and I certainly don't want to have to manage my entire test suite in a single global run() callback. Fortunately, there's a way to dynamically create the tests on a per-file basis, and it doesn't require any special flags, either :-)
To dynamically create It() tests in any test source file using data obtained asynchronously, you can (ab)use the before() hook with a placeholder It() test to ensure mocha waits until before() is run. Here's the example from my answer to a related question, for convenience:
before(function () {
console.log('Let the abuse begin...');
return promiseFn().
then(function (testSuite) {
describe('here are some dynamic It() tests', function () {
testSuite.specs.forEach(function (spec) {
it(spec.description, function () {
var actualResult = runMyTest(spec);
assert.equal(actualResult, spec.expectedResult);
});
});
});
});
});
it('This is a required placeholder to allow before() to work', function () {
console.log('Mocha should not require this hack IMHO');
});

What is the role of describe() in Mocha?

The documentation at the official Mocha site contains this example:
describe('User', function(){
describe('#save()', function(){
it('should save without error', function(done){
var user = new User('Luna');
user.save(function(err){
if (err) throw err;
done();
});
})
})
})
I want to know when I should nest my tests in the describe function and what the basic purpose of describe is. Can I compare the first argument passed to describe to comments in a programming language? Nothing is shown of describe in the output on the console. Is it only for readability purposes, or there is some other use for this function?
Is there anything wrong if I use it like this?
describe('User', function(){
describe('#save()', function(){
var user = new User('Luna');
user.save(function(err){
if (err) throw err;
done();
})
})
})
If I do it this way, the test still passes.
The it call identifies each individual tests but by itself it does not tell Mocha anything about how your test suite is structured. How you use the describe call is what gives structure to your test suite. Here are some of the things that using describe to structure your test suite does for you. Here's an example of a test suite, simplified for the purpose of discussion:
function Foo() {
}
describe("Foo", function () {
var foo;
beforeEach(function () {
foo = new Foo();
});
describe("#clone", function () {
beforeEach(function () {
// Some other hook
});
it("clones the object", function () {
});
});
describe("#equals", function () {
it("returns true when the object passed is the same", function () {
});
it("returns false, when...", function () {
});
});
afterEach(function () {
// Destroy the foo that was created.
// foo.destroy();
});
});
function Bar() {
}
describe("Bar", function () {
describe("#clone", function () {
it("clones the object", function () {
});
});
});
Imagine that Foo and Bar are full-fledged classes. Foo has clone and equals methods. Bar has clone. The structure I have above is one possible way to structure tests for these classes.
(The # notation is used by some systems (like for instance, jsdoc) to indicate an instance field. So when used with a method name, it indicates a method called on an instance of the class (rather than a class method, which is called on the class itself). The test suite would run just as well without the presence of #.)
Provide Banners
Some of Mocha's reporters show the names you give to describe in the reports they produce. For instance, the spec reporter (which you can use by running $ mocha -R spec), would report:
Foo
#clone
✓ clones the object
#equals
✓ returns true when the object passed is the same
✓ returns false, when...
Bar
#clone
✓ clones the object
4 passing (4ms)
Help Select Parts to Run
If you want to run only some of the tests, you can use the --grep option. So if you care only about the Bar class, you can do $ mocha -R spec --grep Bar, and get the output:
Bar
#clone
✓ clones the object
1 passing (4ms)
Or if you care only about the clone methods of all classes, then $ mocha -R spec --grep '\bclone\b' and get the output:
Foo
#clone
✓ clones the object
Bar
#clone
✓ clones the object
2 passing (5ms)
The value given to --grep is interpreted as a regex so when I pass \bclone\b I'm asking only for the word clone, and not things like clones or cloned.
Provide Hooks
In the example above the beforeEach and afterEach calls are hooks. Each hook affects the it calls that are inside the describe call which is the parent of the hook. The various hooks are:
beforeEach which runs before each individual it inside the describe call.
afterEach which runs after each individual it inside the describe call.
before which runs once before any of the individual it inside the describe call is run.
after which runs once after all the individual it inside the describe call are run.
These hooks can be used to acquire resources or create data structures needed for the tests and then release resources or destroy these structures (if needed) after the tests are done.
The snippet you show at the end of your question won't generate an error but it does not actually contain any test, because tests are defined by it.
It's hard to add to Louis' excellent answer. There are a couple of advantages of the describe block that he didn't mention which are the skip and only functions.
describe.skip(...) {
...
}
will skip this describe and all its nested describe and it functions while:
describe.only(...) {
...
}
will only execute that describe and its nested describe and it functions. The skip() and only() modifiers can also be applied to the it() functions.
To my knowledge, describe is really just there for humans... So we can see different areas of the app. You can nest describe n levels deep.
describe('user',function(){
describe('create',function(){}
});
Describe is just used for the sake of understanding the purpose of the tests , it is also used to logically group the tests . Lets say you are testing the database API's , all the database tests could come under the outer describe , so the outer describe logically groups all the database related . Lets say there are 10 database related API's to test , each of the inner describe functions defines what those tests are ....
The particular role of describe is to indicate which component is being tested and which method of that component is also being tested.
for example, lets say we have a User Prototype
var User = function() {
const self = this;
function setName(name) {
self.name = name
}
function getName(name) {
return self.name;
}
return{setName, getName};
}
module.exports = User;
And it needs to be tested, so a spec file is created for unit test
var assert = require('assert');
var User = require("../controllers/user.controller");
describe("User", function() {
describe('setName', function() {
it("should set the name on user", function() {
const pedro = new User();
name = "Pedro"
pedro.setName(name);
assert(pedro.getName(), name);
});
});
});
It is easy to see that the purpose of describe is indicating the component to be tested and the nested describe methods indicate which methods needs to be tested

Resources