vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

90 lines
2.4 KiB

  1. /**
  2. * Set up mock 2D context, for usage in unit tests.
  3. *
  4. * Adapted from: https://github.com/Cristy94/canvas-mock
  5. */
  6. var canvasMock; // Use one canvas instance for all calls to createElement('canvas');
  7. function replaceCanvasContext (el) {
  8. el.getContext = function() {
  9. return {
  10. fillRect: function() {},
  11. clearRect: function(){},
  12. getImageData: function(x, y, w, h) {
  13. return {
  14. data: new Array(w*h*4)
  15. };
  16. },
  17. putImageData: function() {},
  18. createImageData: function(){ return []},
  19. setTransform: function(){},
  20. drawImage: function(){},
  21. save: function(){},
  22. fillText: function(){},
  23. restore: function(){},
  24. beginPath: function(){},
  25. moveTo: function(){},
  26. lineTo: function(){},
  27. closePath: function(){},
  28. stroke: function(){},
  29. translate: function(){},
  30. scale: function(){},
  31. rotate: function(){},
  32. arc: function(){},
  33. fill: function(){},
  34. //
  35. // Following added for vis.js unit tests
  36. //
  37. measureText: function(text) {
  38. return {
  39. width: 12*text.length,
  40. height: 14
  41. };
  42. },
  43. };
  44. }
  45. };
  46. /**
  47. * Overrides document.createElement(), in order to supply a custom canvas element.
  48. *
  49. * In the canvas element, getContext() is overridden in order to supply a simple
  50. * mock object for the 2D context. For all other elements, the call functions unchanged.
  51. *
  52. * The override is only done if there is no 2D context already present.
  53. * This allows for normal running in a browser, and for node.js the usage of 'canvas'.
  54. *
  55. * @param {object} the current global window object. This can possible come from module 'jsdom',
  56. * when running under node.js.
  57. */
  58. function mockify(window) {
  59. var d = window.document;
  60. var f = window.document.createElement;
  61. // Check if 2D context already present. That happens either when running in a browser,
  62. // or this is node.js with 'canvas' installed.
  63. var ctx = d.createElement('canvas').getContext('2d');
  64. if (ctx !== null && ctx !== undefined) {
  65. //console.log('2D context is present, no need to override');
  66. return;
  67. }
  68. window.document.createElement = function(param) {
  69. if (param === 'canvas') {
  70. if (canvasMock === undefined) {
  71. canvasMock = f.call(d, 'canvas');
  72. replaceCanvasContext(canvasMock);
  73. }
  74. return canvasMock;
  75. } else {
  76. return f.call(d, param);
  77. }
  78. };
  79. }
  80. module.exports = mockify;