量角器测试中的request-promise + co API触发器

request-promise + co API trigger in protractor test

本文关键字:co API 触发器 request-promise 测试 量角器      更新时间:2023-09-26

我想从量角器测试中调用module.api.create。参考本方案:-链多节点http请求我使用request-promise + co像这样:-

//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);

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

在我的Spec/Test中添加

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

我面临的问题是,即使没有调用"api.module1.create;"行,要求行"api = require('../../api/api');"在每次执行测试时自动调用create

From co README:

co@4.0.0已经发布,现在依赖于承诺。这是迈向async/await提议的垫脚石。主要的API更改是如何调用co()。之前,co返回一个"thunk",然后用回调函数和可选参数调用它。现在,co()返回一个promise。

我相信你正在寻找co.wrap,它返回一个执行生成器并返回一个承诺的函数(这个函数也可以被称为thunk)。仅使用co急切地执行生成器并返回执行生成器的结果。

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()  

您也可以自己包装一个函数,它与co.wrap做同样的事情,并允许您在之后做更多的事情。

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(...)
}