Search code examples
javascriptprotractorgeneratorrequire

request-promise + co API trigger in protractor test


I want to call module.api.create from my protractor test. Referring this solution:- Chain multiple Node http request I am using request-promise + co like this:-

//api/module1.js
var co = require('co');
var rp = require('request-promise');

exports.create =  co(function* def() {
    var response, token;
    urlLogin.body.username = username;
    response = yield rp(urlLogin);
    //extract token and run other APIs
    ...
}).catch(err => console.log);

And

//api/api.js 
var module1= require('./module1'),
exports.module1= function (){
  return module1;
}; 

In my Spec/Test I am adding

api = require('../../api/api');
api.module1.create;  

Issue i am facing is than even without calling the "api.module1.create;" line, the require line "api = require('../../api/api');" is calling the create automatically every-time the test is executed


Solution

  • From the co README:

    co@4.0.0 has been released, which now relies on promises. It is a stepping stone towards the async/await proposal. The primary API change is how co() is invoked. Before, co returned a "thunk", which you then called with a callback and optional arguments. Now, co() returns a promise.

    I believe you're looking for co.wrap, which returns a function that executes the generator and returns a promise (this function may also be known as a thunk). Using just co eagerly executes the generator and returns the result of executing the generator.

    const co = require('co')
    
    co(function* () {
      // this will run
      console.log('hello from plain co!')
    })
    
    co.wrap(function* () {
      // this won't run because we never call the returned function
      console.log('hello from wrapped co 1!')
    })
    
    const wrappedfn = co.wrap(function* () {
      // this runs because we call the returned function
      console.log('hello from wrapped co 2!')
    })
    
    wrappedfn()  
    

    You can also wrap a function by yourself, which does the same thing as co.wrap and lets you do more stuff afterwards.

    exports.create = function() {
      return co(function* () {
        // this will run only when exports.create is called
        console.log('hello from plain co!')
      })
      // If you want to do stuff after and outside the generator but inside the enclosing function
      .then(...)
    }