test-helper.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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: onend});
  20. return handler;
  21. function onend(){
  22. cb(null, handler.events.reduce(eventReducer, []));
  23. }
  24. };
  25. function eventReducer(events, arr){
  26. if(arr[0] === "onerror" || arr[0] === "onend");
  27. else if(arr[0] === "ontext" && events.length && events[events.length - 1].event === "text"){
  28. events[events.length - 1].data[0] += arr[1];
  29. } else {
  30. events.push({
  31. event: arr[0].substr(2),
  32. data: arr.slice(1)
  33. });
  34. }
  35. return events;
  36. }
  37. function getCallback(expected, done){
  38. var repeated = false;
  39. return function(err, actual){
  40. assert.ifError(err);
  41. try {
  42. assert.deepEqual(expected, actual, "didn't get expected output");
  43. } catch(e){
  44. e.expected = JSON.stringify(expected, null, 2);
  45. e.actual = JSON.stringify(actual, null, 2);
  46. throw e;
  47. }
  48. if(repeated) done();
  49. else repeated = true;
  50. };
  51. }
  52. exports.mochaTest = function(name, root, test){
  53. describe(name, readDir);
  54. function readDir(){
  55. var dir = path.join(root, name);
  56. fs
  57. .readdirSync(dir)
  58. .filter(RegExp.prototype.test, /^[^\._]/) //ignore all files with a leading dot or underscore
  59. .map(function(name){
  60. return path.join(dir, name);
  61. })
  62. .map(require)
  63. .forEach(runTest);
  64. }
  65. function runTest(file){
  66. it(file.name, function(done){
  67. test(file, getCallback(file.expected, done));
  68. });
  69. }
  70. };