jest.setup.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* istanbul ignore file */
  2. require("jest-fetch-mock").enableMocks();
  3. require("@testing-library/jest-dom");
  4. // Mock HTMLMediaElement data and methods not implemented by jsdom.
  5. window.HTMLMediaElement.prototype._mock = {
  6. paused: true,
  7. duration: Number.NaN,
  8. _loaded: false,
  9. // Emulates the media file loading
  10. _load: function mediaInit(media) {
  11. media.dispatchEvent(new Event("loadedmetadata"));
  12. media.dispatchEvent(new Event("loadeddata"));
  13. media.dispatchEvent(new Event("canplaythrough"));
  14. },
  15. // Reset to the initial state
  16. _resetMock: function resetMock(media) {
  17. media._mock = Object.assign({}, window.HTMLMediaElement.prototype._mock);
  18. },
  19. _supportsTypes: ["video/mp4", "video/webm", "video/ogg", "audio/mp3", "audio/webm", "audio/ogg", "audio/wav"],
  20. };
  21. // Get "paused" value, it is automatically set to true / false when we play / pause the media.
  22. Object.defineProperty(window.HTMLMediaElement.prototype, "paused", {
  23. get() {
  24. return this._mock.paused;
  25. },
  26. configurable: true,
  27. });
  28. // Get and set media duration
  29. Object.defineProperty(window.HTMLMediaElement.prototype, "duration", {
  30. get() {
  31. return this._mock.duration;
  32. },
  33. set(value) {
  34. // Reset the mock state to initial (paused) when we set the duration.
  35. this._mock._resetMock(this);
  36. this._mock.duration = value;
  37. },
  38. configurable: true,
  39. });
  40. // Load the media file
  41. window.HTMLMediaElement.prototype.load = function loadMock() {
  42. if (!this._mock._loaded) {
  43. // emulate the media file load and metadata initialization
  44. this._mock._load(this);
  45. }
  46. this.dispatchEvent(new Event("load"));
  47. };
  48. // Start the playback.
  49. window.HTMLMediaElement.prototype.play = function playMock() {
  50. if (!this._mock._loaded) {
  51. // emulate the media file load and metadata initialization
  52. this._mock._load(this);
  53. }
  54. this._mock.paused = false;
  55. this.dispatchEvent(new Event("play"));
  56. };
  57. // Pause the playback
  58. window.HTMLMediaElement.prototype.pause = function pauseMock() {
  59. this._mock.paused = true;
  60. this.dispatchEvent(new Event("pause"));
  61. };
  62. // Can play the media file
  63. window.HTMLMediaElement.prototype.canPlayType = function canPlayTypeMock(type) {
  64. return this._mock._supportsTypes.includes(type) ? "maybe" : "";
  65. };