For testing my NodeJs Server I am using mocha and supertest . But I don`t like the simplicity of my tests, they actually are not checking server properly.
// simple test
describe('Server GET requests', function() {
it('GET /index', function(done){
request(app)
.get('/')
.expect(200, done)
})
})
So the test is only checking that server has a response for the request, but is not checking the correctnes of the response. I want test to be looking something like this:
// test should be
describe('Server GET requests', function() {
it('GET /index', function(done){
request(app)
.get('/')
.expect(200)
.end(function (err, res) {
if (err != null)
done(err);
checkContentTitle('Home Page', res.text);
checkContent(params, res.text);
done();
})
})
})
// function to check the title of the send result
function checkContentTitle(title, htmlText){
// checkTitle(title, parse('title', htmlText));
}
But I can`t find the propriate way of doing this.
What is a good practice of testing server responses, GET-request responses for example? I suppose I need some tols like html\\DOM parser, to get specific tags? Can somebody advise proper tools?
Try the cheerio library:
It works like jquery for selecting DOM elements, very easy to use.
You can compare the cheerio returned values with the assertions that you want.
Example of test/test.js:
var assert = require("assert");
var cheerio = require('cheerio');
var request = require('request');
describe('domtesting', function() {
describe('GET /', function () {
it('title must be Hello', function (done) {
request('http://example.com/',function(err,response,html){
if(!err){
var $ = cheerio.load(html);
assert.equal('Hello', $('title').text());
done();
}
else{
console.log(err);
}
})
});
});
});
Use named functions or mocha promise syntax in order to get more readable and maintainable code. I also used the request library for launch http request inside tests.
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.