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.

92 lines
2.5 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. text: function(){},
  23. fillText: function(){},
  24. restore: function(){},
  25. beginPath: function(){},
  26. moveTo: function(){},
  27. lineTo: function(){},
  28. closePath: function(){},
  29. stroke: function(){},
  30. translate: function(){},
  31. scale: function(){},
  32. rotate: function(){},
  33. circle: function(){},
  34. arc: function(){},
  35. fill: function(){},
  36. //
  37. // Following added for vis.js unit tests
  38. //
  39. measureText: function(text) {
  40. return {
  41. width: 12*text.length,
  42. height: 14
  43. };
  44. }
  45. };
  46. }
  47. }
  48. /**
  49. * Overrides document.createElement(), in order to supply a custom canvas element.
  50. *
  51. * In the canvas element, getContext() is overridden in order to supply a simple
  52. * mock object for the 2D context. For all other elements, the call functions unchanged.
  53. *
  54. * The override is only done if there is no 2D context already present.
  55. * This allows for normal running in a browser, and for node.js the usage of 'canvas'.
  56. *
  57. * @param {object} window - current global window object. This can possible come from module 'jsdom',
  58. * when running under node.js.
  59. */
  60. function mockify(window) {
  61. var d = window.document;
  62. var f = window.document.createElement;
  63. // Check if 2D context already present. That happens either when running in a browser,
  64. // or this is node.js with 'canvas' installed.
  65. var ctx = d.createElement('canvas').getContext('2d');
  66. if (ctx !== null && ctx !== undefined) {
  67. //console.log('2D context is present, no need to override');
  68. return;
  69. }
  70. window.document.createElement = function(param) {
  71. if (param === 'canvas') {
  72. if (canvasMock === undefined) {
  73. canvasMock = f.call(d, 'canvas');
  74. replaceCanvasContext(canvasMock);
  75. }
  76. return canvasMock;
  77. } else {
  78. return f.call(d, param);
  79. }
  80. };
  81. }
  82. module.exports = mockify;