I'm writing some tests for an async node.js function which returns a promise using the Mocha, Chai and Sinon libraries.
Let's say this is my function:
function foo(params) {
return (
mkdir(params)
.then(dir => writeFile(dir))
)
}
mkdir & writeFile are both async functions which return promises.
I need to test that mkdir is being called once with the params given to foo.
How can I do this?
I've seen quite a few examples on how to assert the overall return value of foo (sinon-as-promised is super helpful for that) but non about how to make sure individual functions are being called inside the promise.
Maybe I'm overlooking something and this is not the right way to go?
mkdir isn't called asynchronously here, so it's rather trivial to test:
mkdir = sinon.stub().resolves("test/dir")
foo(testparams)
assert(mkdir.calledOnce)
assert(mkdir.calledWith(testparams))
…
If you want to test that writeFile was called, that's only slightly more complicated - we have to wait for the promise returned by foo before asserting:
… // mdir like above
writeFile = sinon.stub().resolves("result")
return foo(testparams).then(r => {
assert.strictEqual(r, "result")
assert(writeFile.calledOnce)
assert(writeFile.calledWith("test/dir"))
…
})
You can mock the mkdir function then use setTimeout to check whether or not this function is called.
describe('foo', () => {
it('should call mkdir', () => {
return new Promise((resolve, reject) => {
let originalFunction = mkdir;
let timer = setTimeout(() => {
reject(`mkdir has not been called`);
});
mkdir = (...params) => new Promise(mkdirResolve => {
//restore the original method as soon as it is invoked
mkdir = originalMethod;
clearTimeout(timer);
mkdirResolve(someExpectedData);
resolve();
});
foo(params);
});
});
});
Related
I'm not looking for jQuery solutions please. I tried using the Promise method, and it wouldn't work either I'm trying the callback method but no luck. For right now, as a test I just want it to print something to the console. I'll do the actual code after.
I have a JSFIDDLE HERE for your coding pleasure
This is the callback method I am trying now as I think it's the simplest
const logoAnimation = () => {
this.logo.classList.add('fade-out-zoom-out');
this.blueCnt.classList.add('fade-out');
this.circWrapper.classList.add('dashed-border');
this.clickAbove.classList.add('text-fade-out');
this.welcome.classList.add('text-fade-in');
}
const rotateBorder = () => {
console.log('I run after animation')
}
const render = () => {
console.log(logoAnimation())
logoAnimation(() => {
rotateBorder();
})
}
I did try the Promise method... I'll take either one to be frank (An explanation of it would be ever better please)
function logoAnimation() {
return new Promise(function(resolve, reject) {
this.logo.classList.add('fade-out-zoom-out');
this.blueCnt.classList.add('fade-out');
this.circWrapper.classList.add('dashed-border');
this.clickAbove.classList.add('text-fade-out');
this.welcome.classList.add('text-fade-in');
})
}
const rotateBorder = () => {
console.log('I run after animation')
}
function render() {
logoAnimation().then(function () {
rotateBorder()
})
}
Then just an onclick call from somewhere
<img class="logo" id="logo" onclick="render()" src="/path/img"/>
Your problem is essentially the same in both versions.
In the first one the implementation of logoAnimation doesn't care about the callback you pass it - in fact it doesn't accept any arguments at all, so it will happily ignore anything passed to it. If you intend to pass it a callback, then you need to ensure that you call it ("call it back" - this is where the term "callback" comes from!) inside the function:
const logoAnimation = (callback) => {
this.logo.classList.add('fade-out-zoom-out');
this.blueCnt.classList.add('fade-out');
this.circWrapper.classList.add('dashed-border');
this.clickAbove.classList.add('text-fade-out');
this.welcome.classList.add('text-fade-in');
callback();
}
In the Promise version, you likewise never call resolve, which is the function passed in to the .then handler. So to get that version to work, you would need to change the implementation like this:
function logoAnimation() {
return new Promise(function(resolve, reject) {
this.logo.classList.add('fade-out-zoom-out');
this.blueCnt.classList.add('fade-out');
this.circWrapper.classList.add('dashed-border');
this.clickAbove.classList.add('text-fade-out');
this.welcome.classList.add('text-fade-in');
resolve();
})
}
I will note that, although in general I'm a big fan of using Promises for asynchronous code rather than old-style spaghetti callbacks, there's nothing asynchronous going on in your examples so I see no need for Promises - I'd just stick with the callback-based version, assuming you need callers of logoAnimation to specify what should happen next.
Unfortunately, css transitions are out of control of JavaScript. Your problem is not with the order of functions.
In order to achieve what you want, you should use setTimeout function and calculate those durations yourself.
You can use a "wait" function in order to mimic waiting:
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
let logo = document.getElementById('logo');
let blueCnt = document.getElementById('blueCnt');
let circWrapper = document.getElementById('circWrapper');
let clickAbove = document.getElementById('clickAbove');
let welcome = document.getElementById('welcome');
function logoAnimation() {
this.logo.classList.add('fade-out-zoom-out');
this.blueCnt.classList.add('fade-out');
this.circWrapper.classList.add('dashed-border');
this.clickAbove.classList.add('text-fade-out');
this.welcome.classList.add('text-fade-in');
}
const rotateBorder = () => {
console.log('I run after animation')
}
function render() {
logoAnimation()
wait(1000).then(rotateBorder)
}
Also pay attention that if you do not call the resolve function inside a Promise callback, it won't fulfill and your function call won't reach the chained .then
If you want to run 2 synchronous functions in sequence, you can just run them one at a time:
func1();
func2(); // Only runs after func1 has completed.
A quick and dirty solution would be to use a timeout:
const logoAnimation = () => {
this.logo.classList.add('fade-out-zoom-out');
this.blueCnt.classList.add('fade-out');
this.circWrapper.classList.add('dashed-border');
this.clickAbove.classList.add('text-fade-out');
this.welcome.classList.add('text-fade-in');
setTimeout(()=>{
rotateBorder();
}, 3000);
}
I have an async function f that calls another async function g. To test if f calls g, I'm stubbing g using sinon and assert it's been called using should.js.
'use strict';
require('should-sinon');
const sinon = require('sinon');
class X {
async f(n) {
await this.g(n);
// this.g(n); // I forget to insert `await`!
}
async g(n) {
// Do something asynchronously
}
}
describe('f', () => {
it('should call g', async () => {
const x = new X();
sinon.stub(x, 'g').resolves();
await x.f(10);
x.g.should.be.calledWith(10);
});
});
But this test passes even when I forget to use await when calling g in f.
One of the ways to catch this error is to make the stub return a dummy promise and check if its then is called.
it('should call g', async () => {
const x = new X();
const dummyPromise = {
then: sinon.stub().yields()
};
sinon.stub(x, 'g').returns(dummyPromise);
await x.f(10);
x.g.should.be.calledWith(10);
dummyPromise.then.should.be.called();
});
But this is a bit bothersome. Are there any convenient ways to do this?
Your example for f shows flawed code design which becomes more obvious if you write the same function without async/await syntax:
f(n) {
return g(n).then(()=>{});
}
This achieves the same behavior - whether g resolved becomes hard to tell (assuming you don't know if f returned g's promise, which is the same as not knowing whether f awaited g). If f is not interested in the result of g it should just simply return it, not hide it. Then you can simply test for the result.
If your point is that f might have to trigger several async calls sequentially awaiting several g_1, g_2,... to resolve, then you can build a test chain by asserting in the stub of g_n+1 that the dummy-promise of g_n has been resolved. In general your approach to test a dummy-promise for its status is fine.
Instead of stubbing then, you're best off stubbing g in such a way that it sets some boolean on the next event loop iteration. Then, you can check this boolean after calling f to make sure f waited for it:
it('should call g', async () => {
const x = new X();
let gFinished = false;
sinon.stub(x, 'g').callsFake(() => {
return new Promise((resolve) => {
setImmediate(() => {
gFinished = true;
resolve();
});
});
});
await x.f(10);
x.g.should.be.calledWith(10);
gFinished.should.be.true();
});
Edit: Of course, this isn't a perfect guarantee because you could have f wait on any promise that waits at least as long as it takes for g to resolve. Like so:
async f(n) {
this.g(n);
await new Promise((resolve) => {
setImmediate(() => {
resolve();
});
});
}
This would cause the test I wrote to pass, even though it's still incorrect. So really it comes down to how strict you're trying to be with your tests. Do you want it to be literally impossible to have a false positive? Or is it ok if some obvious trickery can potentially throw it off?
In most cases I find that the latter is ok, but really that's up to you and/or your team.
I have a bit of an unusual problem that I haven't found any solution for and I've been trying for quite some time. I have created a function called delay that basically creates a new Promise which resolves itself after a given amount of time. The purpose of this function is to be able to cause a delay in a chain of promises. It looks a bit like this:
const delay = ms => new Promise((resolve, reject) => {
setTimeout(resolve, ms);
});
let test = '';
const func = () => {
delay(1000).then(() => {
test = 'kek';
});
};
describe('unit tests', () => {
it('test function func', () => {
// Act
func();
// Assert
expect(test).toEqual('kek');
});
});
The problem is testing, the unit test I have provided in this example will fail because it's only after the 1000 ms delay that the variable test is set to kek.
I have tried the usual solutions like having a setTimeout inside the unit test, and also tried with jasmine.clock().tick(1001) before asserting but I can't get it to work.
Any ideas?
I actually proposed to do this (at lolex, the timers library) and am now convinced that it's a good thing that this is impossible to override the scheduler for that reason. That's because it can change the ordering of calls which can be very problematic.
Promises always resolve asynchronously, you'll have to make your test async and return the promise.
Here is how you'd write that test with an async function:
describe('unit tests', () => {
it('test function func', async () => {
// Act
let promise = func(); // wait for it to be ready
clock.tick(1001);
await promise; // wait for the promise to complete.
// Assert
expect(test).toEqual('kek');
});
});
This way you won't wait 1000 ms but the test will still work.
This works for me,
import {fakeAsync, tick } from '#angular/core/testing';
describe('When ngOnInit is invoked', () => {
it('should wait and redirect to next page', fakeAsync( () => {
component.ngOnInit(); // contains delay inside
tick(2000); // time to wait
expect(routerService.navigate).toHaveBeenCalledWith('nextStep');
}));
});
I want to be able to just return the arguments that a stub receives passed to a promise, is this possible:
Impl:
function(arg) {
return db.find(arg)
.then(result => {
return fnIWantToStub(result);
})
.then(nextResult => {
return done()
});
Test:
var stub = sinon.stub(fnIWantToStub);
stub.returns(PassedThruArgsThatReturnsAPromise);
Can this be done?
The docs state that you can return an arg at a given index.
stub.returnsArg(index);
I don't think there is a blanket return all args.
(UPDATE after question edit)
You could stub the db.find function and resolve it. I use mocha and chai.
const dbStub = sinon.stub(db, 'find);
const expected = {..};
dbStub.returns(Promise.resolve(someDataFixture));
const result = functionUnderTest(args);
// using chaiAsPromised
return expect(result).to.eventually.equal(expected);
Note you have to return to get Mocha to run through the promise. You can also use mocha's done callback. Although quite often I'll just use a Promise.
Checkout http://staxmanade.com/2015/11/testing-asyncronous-code-with-mochajs-and-es7-async-await/
You have a prototype object Foo with two async method calls, bar and baz.
var bob = new Foo()
Foo.prototype.bar = function land(callback) {
setTimeout(function() {
callback()
console.log('bar');
}, 3000);
};
Foo.prototype.baz = function land(callback) {
setTimeout(function() {
callback()
console.log('baz');
}, 3000);
};
We want to do bob.bar().baz() and have it log "bar" and "baz" sequentially.
If you cannot modify the method calls (including passing in your callback function), how can you pass a default callback into these method calls?
Some ideas:
Wrap "bob" with decorator (still fuzzy on how to implement, could use a small example)
Modify constructor to assign default callback if none assigned (have not considered if this is possible or not)
Use a generator wrapper that will continue to call next method until none are left?
The more recommended way instead is to use promises as this is the community-wide practice to do async work.
We want to do bob.bar().baz() and have it log "bar" and "baz"
sequentially.
Why would you want to do that just to achieve this bob.bar().baz() "syntax"? You could do it pretty neatly using the Promise API w/o additional efforts to make that syntax work that indeed increases code complexity reducing the actual readability.
So, you might want to consider using the promise-based approach like this. It offers much flexibility than what you would have achieved with your approach:
Foo.prototype.bar = function () {
return new Promise(function (resolve) {
setTimeout(function () {
resolve()
console.log('bar');
}, 3000);
};
};
Foo.prototype.baz = function () {
return new Promise(function (resolve) {
setTimeout(function () {
resolve()
console.log('baz');
}, 3000);
};
};
Now you'd do this to run them sequentially one after another:
var bob = new Foo();
bob.bar().then(function() {
return bob.baz();
});
// If you're using ES2015+ you could even do:
bob.bar().then(() => bob.baz());
If you need to chain more functions you could simply do it:
bob.bar()
.then(() => bob.baz())
.then(() => bob.anotherBaz())
.then(() => bob.somethingElse());
Anyway, if you're not used to using promises you might want to read this
Warning this isn't quite right yet. Ideally we'd subclass Promise and have proper then/catch functionality but there are some caveats with subclassing bluebird Promise. The idea is to store an internal array of promise generating functions, then when a Promise is waited on (then/await) serially wait on those promises.
const Promise = require('bluebird');
class Foo {
constructor() {
this.queue = [];
}
// promise generating function simply returns called pGen
pFunc(i,pGen) {
return pGen();
}
bar() {
const _bar = () => {
return new Promise( (resolve,reject) => {
setTimeout( () => {
console.log('bar',Date.now());
resolve();
},Math.random()*1000);
})
}
this.queue.push(_bar);
return this;
}
baz() {
const _baz = () => {
return new Promise( (resolve,reject) => {
setTimeout( () => {
console.log('baz',Date.now());
resolve();
},Math.random()*1000);
})
}
this.queue.push(_baz);
return this;
}
then(func) {
return Promise.reduce(this.queue, this.pFunc, 0).then(func);
}
}
const foo = new Foo();
foo.bar().baz().then( () => {
console.log('done')
})
result:
messel#messels-MBP:~/Desktop/Dropbox/code/js/async-chain$ node index.js
bar 1492082650917
baz 1492082651511
done
If you want to avoid callback hell and keep your sanity ES6 promises are the most appropriate approach for the sake of functional programming. You just chain up your sequential asynchronous tasks in the asynchronous timeline just like working in a synchronous timeline.
In this particular case you just need to promisify your asynchronous functions. Assume that your asynch functions takes a data and a callback like asynch(data,myCallback). Let us assume that the callback is error first type.
Such as;
var myCallback = (error,result) => error ? doErrorAction(error)
: doNormalAction(result)
When your asynch function is promisified, you will actually be returned a function which takes your data and returns a promise. You are expected to apply myCallback at the then stage. The return value of myCallback will then be passed to the next stage at where you can invoke another asynch function supplied with the return value of myCallback and this goes on and on as long as you need. So let's see how we shall implement this abstract to your workflow.
function Foo(){}
function promisify(fun){
return (data) => new Promise((resolve,reject) => fun(data, (err,res) => err ? reject(err) : resolve(res)));
}
function myCallback(val) {
console.log("hey..! i've got this:",val);
return val;
}
var bob = new Foo();
Foo.prototype.bar = function land(value, callback) {
setTimeout(function() {
callback(false,value*2); // no error returned but value doubled and supplied to callback
console.log('bar');
}, 1000);
};
Foo.prototype.baz = function land(value, callback) {
setTimeout(function() {
callback(false,value*2); // no error returned but value doubled and supplied to callback
console.log('baz');
}, 1000);
};
Foo.prototype.bar = promisify(Foo.prototype.bar);
Foo.prototype.baz = promisify(Foo.prototype.baz);
bob.bar(1)
.then(myCallback)
.then(bob.baz)
.then(myCallback)