tests.js 1.5 KB

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