Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 节点请求模块在测试期间未获得响应_Javascript_Node.js_Request_Mocha.js_Chai - Fatal编程技术网

Javascript 节点请求模块在测试期间未获得响应

Javascript 节点请求模块在测试期间未获得响应,javascript,node.js,request,mocha.js,chai,Javascript,Node.js,Request,Mocha.js,Chai,我是node新手,使用node.js模块向google发出http请求 然后,我使用测试库chai来测试http请求是否成功。考试不及格,我一辈子都不明白为什么 代码如下: //validator.js var request = require('request') export function validateWeb(website) { request('http://www.google.com', function (error, response, body) {

我是node新手,使用node.js模块向google发出http请求

然后,我使用测试库chai来测试http请求是否成功。考试不及格,我一辈子都不明白为什么

代码如下:

//validator.js
var request = require('request')

export function validateWeb(website) {
   request('http://www.google.com', function (error, response, body) {
       if (!error && response.statusCode == 200) {
           console.log("Inside the successful callback!") //not being printed
           return response.statusCode
       }
   })
}
//validator_spec.js
import {validateWeb} from '../src/validator'

describe ('Validator', () => {
    describe ('correctly validates', () => {
         it('existing site', () => {
             const site = "http://www.google.com"
             var result = validateWeb(site)
             expect(result).to.equal(200)
         })
    })
})
测试如下:

//validator.js
var request = require('request')

export function validateWeb(website) {
   request('http://www.google.com', function (error, response, body) {
       if (!error && response.statusCode == 200) {
           console.log("Inside the successful callback!") //not being printed
           return response.statusCode
       }
   })
}
//validator_spec.js
import {validateWeb} from '../src/validator'

describe ('Validator', () => {
    describe ('correctly validates', () => {
         it('existing site', () => {
             const site = "http://www.google.com"
             var result = validateWeb(site)
             expect(result).to.equal(200)
         })
    })
})

我错过了什么?当我运行
npm测试时,测试本身已启动并正在运行(但断言失败)。

您的验证器是异步的,因此您需要提供并使用回调(或承诺):

然后在你的测试中:

//validator_spec.js
import {validateWeb} from '../src/validator'

describe ('Validator', () => {
    describe ('correctly validates', () => {
         it('existing site', (done) => {
             const site = "http://www.google.com"
             validateWeb(site, (err, result) => {
                 if (err) return done(err)
                 expect(result).to.equal(200)
             })
         })
    })
})

断言仍将失败。一个简单的
GET
to将收到一个HTTP状态为302的回复。@NehalJWani
请求库默认遵循重定向。哦。我懂了。我不知道。