gpt4 book ai didi

javascript - Node.js 和 Mocha/Should(JavaScript、ES6): Code not executed although it looks like it should

转载 作者:行者123 更新时间:2023-12-01 03:22:44 25 4
gpt4 key购买 nike

我尝试使用 mocha/should 和 request 在 Node.js 项目中编写一些测试代码。

我的代码使用一些网址初始化一个数组,以便向远程服务器发送 GET 请求并检查响应的内容。

我的模型现在只需要打印出响应,但由于某种原因,流程永远不会到达那里。

请注意,我有一个 for 循环。在循环内,第一个控制台日志打印出内容,但是由于某种原因,该循环内的其余代码被跳过。我在 Debug模式下设置了断点,但我的代码仅到达循环内的第一个 console.log() 并且请求部分被跳过。

我也尝试使用请求的未 promise 版本(流和所有),但我遇到了同样的问题 - 代码从未到达该请求行,所以当然它不会进一步打印内部的任何内容。

这与nodejs内部的异步工作有关吗?还有别的东西吗?

我错过了什么?

'use strict';
const Promise = require('bluebird')
, _ = require('underscore')
, should = require('should')
, r = require('request')
, request = Promise.promisifyAll(r.defaults({jar: true}))
, client = require('../whatever/someClient')
, testConfig = require('../config/test-config')
;

Promise.longStackTraces();

class someFeatureTestSet {

constructor() {
//...
this.client = client.getUser();
//...
}

static create() { return new someFeatureTestSet(); }

//... some other consts and functions

initURLs(someUrlParamVal) {
return Array
.apply(null, Array(someUrlParamVal))
.map((x, idx) =>
`http://example.com/whatever?c=${someUrlParamVal}`
);
}

runTests() {
const client = this.client;
const someFeatureTestSet = this;

describe('get stuff', () => {

it('should bla', () => {
const productsLinks = this.initURLs('123');

for (let x in productsLinks) {
console.log(productsLinks[x]); //gets printed, no problem
request.getAsync({ uri: productsLinks[x] })
.then(res => { //code never gets here. why?
console.log(res); //code never gets here. why?
})
}

});

} );

}

}

module.exports = someFeatureTestSet;

const createTestSet = () => someFeatureTestSet.create();

createTestSet().client().runTests();

最佳答案

运行异步测试后,您需要返回 Promise 或调用 done() 回调。由于您在循环中运行异步请求,因此您需要将请求 promise 累积在数组中并使用 Promise.all()

it('should bla', () => {
const productsLinks = this.initURLs('123');
let requests = [];

for (let x in productsLinks) {
console.log(productsLinks[x]); //gets printed, no problem
requests.push(request.getAsync({ uri: productsLinks[x] }));
}

return Promise.all(requests);
});

如果您想使用done(),您可以执行以下操作 -

it('should bla', (done) => {
const productsLinks = this.initURLs('123');
let requests = [];

for (let x in productsLinks) {
console.log(productsLinks[x]); //gets printed, no problem
requests.push(request.getAsync({ uri: productsLinks[x] }));
}

Promise
.all(requests)
.then(() => {
done();
})
});

请注意,如果超过运行 Mocha 测试设置的超时,调用 done() 将失败。请参阅此处了解更多信息 - https://mochajs.org/#timeouts

关于javascript - Node.js 和 Mocha/Should(JavaScript、ES6): Code not executed although it looks like it should,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45061921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com