tests.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. var fs = require("fs"),
  2. path = require("path"),
  3. assert = require("assert"),
  4. util = require("util"),
  5. Parser = require("htmlparser2").Parser,
  6. Handler = require("../");
  7. var basePath = path.resolve(__dirname, "cases"),
  8. inspectOpts = { showHidden: true, depth: null };
  9. fs
  10. .readdirSync(basePath)
  11. .filter(RegExp.prototype.test, /\.json$/) //only allow .json files
  12. .map(function(name){
  13. return path.resolve(basePath, name);
  14. })
  15. .map(require)
  16. .forEach(function(test){
  17. it(test.name, function(){
  18. var expected = test.expected;
  19. var handler = new Handler(function(err, actual){
  20. assert.ifError(err);
  21. try {
  22. compare(expected, actual);
  23. } catch(e){
  24. e.expected = util.inspect(expected, inspectOpts);
  25. e.actual = util.inspect(actual, inspectOpts);
  26. throw e;
  27. }
  28. }, test.options);
  29. var data = test.html;
  30. var parser = new Parser(handler, test.options);
  31. //first, try to run the test via chunks
  32. if (test.streaming || test.streaming === undefined){
  33. for(var i = 0; i < data.length; i++){
  34. parser.write(data.charAt(i));
  35. }
  36. parser.done();
  37. }
  38. //then parse everything
  39. parser.parseComplete(data);
  40. });
  41. });
  42. function compare(expected, result){
  43. assert.equal(typeof expected, typeof result, "types didn't match");
  44. if(typeof expected !== "object" || expected === null){
  45. assert.strictEqual(expected, result, "result doesn't equal expected");
  46. } else {
  47. for(var prop in expected){
  48. assert.ok(prop in result, "result didn't contain property " + prop);
  49. compare(expected[prop], result[prop]);
  50. }
  51. }
  52. }