test-helper.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. var htmlparser2 = require(".."),
  2. fs = require("fs"),
  3. path = require("path"),
  4. assert = require("assert"),
  5. Parser = htmlparser2.Parser,
  6. CollectingHandler = htmlparser2.CollectingHandler;
  7. exports.writeToParser = function(handler, options, data){
  8. var parser = new Parser(handler, options);
  9. //first, try to run the test via chunks
  10. for(var i = 0; i < data.length; i++){
  11. parser.write(data.charAt(i));
  12. }
  13. parser.end();
  14. //then parse everything
  15. parser.parseComplete(data);
  16. };
  17. //returns a tree structure
  18. exports.getEventCollector = function(cb){
  19. var handler = new CollectingHandler({onerror: cb, onend: function(){
  20. cb(null, handler.events.reduce(eventReducer, []));
  21. }});
  22. return handler;
  23. };
  24. function eventReducer(events, arr){
  25. if(arr[0] === "onerror" || arr[0] === "onend");
  26. else if(arr[0] === "ontext" && events.length && events[events.length-1].event === "text"){
  27. events[events.length-1].data[0] += arr[1];
  28. } else {
  29. events.push({
  30. event: arr[0].substr(2),
  31. data: arr.slice(1)
  32. });
  33. }
  34. return events;
  35. }
  36. function getCallback(expected, done){
  37. var repeated = false;
  38. return function(err, actual){
  39. assert.ifError(err);
  40. try {
  41. assert.deepEqual(expected, actual, "didn't get expected output");
  42. } catch(e){
  43. e.expected = JSON.stringify(expected, null, 2);
  44. e.actual = JSON.stringify(actual, null, 2);
  45. throw e;
  46. }
  47. if(repeated) done();
  48. else repeated = true;
  49. };
  50. }
  51. exports.mochaTest = function(name, root, test){
  52. describe(name, readDir);
  53. function readDir(cb){
  54. var dir = path.join(root, name);
  55. fs
  56. .readdirSync(dir)
  57. .filter(RegExp.prototype.test, /^[^\._]/) //ignore all files with a leading dot or underscore
  58. .map(function(name){
  59. return path.join(dir, name);
  60. })
  61. .map(require)
  62. .forEach(runTest);
  63. }
  64. function runTest(file){
  65. it(file.name, function(done){
  66. test(file, getCallback(file.expected, done));
  67. });
  68. }
  69. };