fixture.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /* global __karma__ */
  2. 'use strict';
  3. var utils = require('./utils');
  4. function readFile(url, callback) {
  5. var request = new XMLHttpRequest();
  6. request.onreadystatechange = function() {
  7. if (request.readyState === 4) {
  8. return callback(request.responseText);
  9. }
  10. };
  11. request.open('GET', url, false);
  12. request.send(null);
  13. }
  14. function loadConfig(url, callback) {
  15. var regex = /\.(json|js)$/i;
  16. var matches = url.match(regex);
  17. var type = matches ? matches[1] : 'json';
  18. var cfg = null;
  19. readFile(url, function(content) {
  20. switch (type) {
  21. case 'js':
  22. // eslint-disable-next-line
  23. cfg = new Function('"use strict"; var module = {};' + content + '; return module.exports;')();
  24. break;
  25. case 'json':
  26. cfg = JSON.parse(content);
  27. break;
  28. default:
  29. }
  30. callback(cfg);
  31. });
  32. }
  33. function specFromFixture(description, inputs) {
  34. var input = inputs.js || inputs.json;
  35. it(input, function(done) {
  36. loadConfig(input, function(json) {
  37. var chart = utils.acquireChart(json.config, json.options);
  38. if (!inputs.png) {
  39. fail('Missing PNG comparison file for ' + inputs.json);
  40. done();
  41. }
  42. utils.readImageData(inputs.png, function(expected) {
  43. expect(chart).toEqualImageData(expected, json);
  44. utils.releaseChart(chart);
  45. done();
  46. });
  47. });
  48. });
  49. }
  50. function specsFromFixtures(path) {
  51. var regex = new RegExp('(^/base/test/fixtures/' + path + '.+)\\.(png|json|js)');
  52. var inputs = {};
  53. Object.keys(__karma__.files || {}).forEach(function(file) {
  54. var matches = file.match(regex);
  55. var name = matches && matches[1];
  56. var type = matches && matches[2];
  57. if (name && type) {
  58. inputs[name] = inputs[name] || {};
  59. inputs[name][type] = file;
  60. }
  61. });
  62. return function() {
  63. Object.keys(inputs).forEach(function(key) {
  64. specFromFixture(key, inputs[key]);
  65. });
  66. };
  67. }
  68. module.exports = {
  69. specs: specsFromFixtures
  70. };