I am new to node and using the node.js module request to fire an http request to google.
I then use the testing library chai to test whether the http request was successful. The test is failing and I cannot for the life of me understand why.
The code is below:
//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
}
})
}
The test is below:
//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)
})
})
})
What am I missing? The test itself is up and running when I run npm test
(but the assertion is failing).
Your validator is asynchronous so you need to provide and use a callback (or a Promise):
//validator.js
var request = require('request')
export function validateWeb(website, callback) {
request(website, (error, response, body) => {
if (error) return callback(error)
callback(null, response.statusCode)
})
}
Then in your test:
//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)
})
})
})
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.