Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Promises with multiple thens using testdoublejs

I am using testdouble for stubbing calls within my node.js project. This particular function is wrapping a promise and has multiple then calls within the function itself.

function getUser (rethink, username) {
  return new Promise((resolve, reject) => {
  let r = database.connect();
  r.then(conn => database.table(tablename).filter({username}))
   .then(data => resolve(data))
   .error(err => reject(err));
 });
}

So I am wanting to determine if the resolve and reject are handled correctly based on error conditions. Assume there is some custom logic in there that I need to validate.

For my test

import getUser from './user';
import td from 'testdouble';
test(t => {
  const db = td.object();
  const connect = td.function();
  td.when(connect('options')).thenResolve();
  const result = getUser(db, 'testuser');
  t.verify(result);
}

The issue is that the result of connect needs to be a promise, so I use then resolve with a value which needs to be another promise that resolves or rejects.

The line it is relating to is the result of database.connect() is not a promise.

TypeError: Cannot read property 'then' of undefined

Anyone have success with stubbing this type of call with Test Double?

like image 218
ckross01 Avatar asked Mar 21 '17 18:03

ckross01


1 Answers

So figured out the resolution. There are a few things to note in the solution and that we encountered. In short the resolution ended up being this...

td.when(database.connect()).thenResolve({then: (resolve) => resolve('ok')});

This resolves a thenable that is returned when test double sees database connect. Then subsequent calls can also be added.

There is also a part to note if you send in an object to database.connect() you have to be aware that it is doing === equality checking and you will need to have a reference to that object for it to correctly use td.when.

like image 57
ckross01 Avatar answered Sep 25 '22 08:09

ckross01