Best JavaScript code snippet using wpt
eme.test.js
Source:eme.test.js  
...501// Skip this test in Safari, getSupportedKeySystem is never used in Safari.502if (!videojs.browser.IS_ANY_SAFARI) {503  QUnit.test('getSupportedKeySystem error', function(assert) {504    const done = assert.async(1);505    getSupportedKeySystem({'un.supported.keysystem': {}}).catch((err) => {506      assert.equal(err.name, 'NotSupportedError', 'keysystem access request fails');507      done();508    });509  });510}511QUnit.test('errors when missing url/licenseUri or getLicense', function(assert) {512  const options = {513    keySystems: {514      'com.widevine.alpha': {}515    }516  };517  const keySystemAccess = {518    keySystem: 'com.widevine.alpha'519  };520  const done = assert.async(1);521  standard5July2016({522    video: {},523    keySystemAccess,524    options,525    eventBus: getMockEventBus()526  }).catch((err) => {527    assert.equal(528      err,529      'Error: Missing url/licenseUri or getLicense in com.widevine.alpha keySystem configuration.',530      'correct error message'531    );532    done();533  });534});535QUnit.test('errors when missing certificateUri and getCertificate for fairplay', function(assert) {536  const options = {537    keySystems: {538      'com.apple.fps': {url: 'fake-url'}539    }540  };541  const keySystemAccess = {542    keySystem: 'com.apple.fps'543  };544  const done = assert.async();545  standard5July2016({546    video: {},547    keySystemAccess,548    options549  }).catch((err) => {550    assert.equal(551      err,552      'Error: Missing getCertificate or certificateUri in com.apple.fps keySystem configuration.',553      'correct error message'554    );555    done();556  });557});558QUnit.test('rejects promise when getCertificate throws error', function(assert) {559  const getCertificate = (options, callback) => {560    callback('error fetching certificate');561  };562  const options = {563    keySystems: {564      'com.widevine.alpha': {565        url: 'some-url',566        getCertificate567      }568    }569  };570  const keySystemAccess = {571    keySystem: 'com.widevine.alpha'572  };573  const done = assert.async(1);574  standard5July2016({575    video: {},576    keySystemAccess,577    options,578    eventBus: getMockEventBus()579  }).catch((err) => {580    assert.equal(err, 'error fetching certificate', 'correct error message');581    done();582  });583});584QUnit.test('rejects promise when createMediaKeys rejects', function(assert) {585  const options = {586    keySystems: {587      'com.widevine.alpha': 'some-url'588    }589  };590  const keySystemAccess = {591    keySystem: 'com.widevine.alpha',592    createMediaKeys: () => {593      return Promise.reject();594    }595  };596  const done = assert.async(1);597  standard5July2016({598    video: {},599    keySystemAccess,600    options,601    eventBus: getMockEventBus()602  }).catch((err) => {603    assert.equal(604      err, 'Failed to create and initialize a MediaKeys object',605      'uses generic message'606    );607    done();608  });609});610QUnit.test('rejects promise when createMediaKeys rejects', function(assert) {611  const options = {612    keySystems: {613      'com.widevine.alpha': 'some-url'614    }615  };616  const keySystemAccess = {617    keySystem: 'com.widevine.alpha',618    createMediaKeys: () => {619      return Promise.reject('failed creating mediaKeys');620    }621  };622  const done = assert.async(1);623  standard5July2016({624    video: {},625    keySystemAccess,626    options,627    eventBus: getMockEventBus()628  }).catch((err) => {629    assert.equal(err, 'failed creating mediaKeys', 'uses specific error when given');630    done();631  });632});633QUnit.test('rejects promise when addPendingSessions rejects', function(assert) {634  let rejectSetServerCertificate = true;635  const rejectGenerateRequest = true;636  let rejectSetMediaKeys = true;637  const options = {638    keySystems: {639      'com.widevine.alpha': {640        url: 'some-url',641        getCertificate: (emeOptions, callback) => {642          callback(null, 'some certificate');643        }644      }645    }646  };647  const keySystemAccess = {648    keySystem: 'com.widevine.alpha',649    createMediaKeys: () => {650      return Promise.resolve({651        setServerCertificate: () => resolveReject(652          rejectSetServerCertificate,653          'setServerCertificate failed'654        ),655        createSession: () => {656          return {657            addEventListener: () => {},658            generateRequest: () => resolveReject(659              rejectGenerateRequest,660              'generateRequest failed'661            )662          };663        }664      });665    }666  };667  const video = {668    setMediaKeys: () => resolveReject(rejectSetMediaKeys, 'setMediaKeys failed')669  };670  const done = assert.async(3);671  const callbacks = [];672  const test = (errMessage, testDescription) => {673    video.mediaKeysObject = undefined;674    standard5July2016({675      video,676      keySystemAccess,677      options,678      eventBus: getMockEventBus()679    }).catch((err) => {680      assert.equal(err, errMessage, testDescription);681      done();682      if (callbacks[0]) {683        callbacks.shift()();684      }685    });686  };687  callbacks.push(() => {688    rejectSetServerCertificate = false;689    test('setMediaKeys failed', 'second promise fails');690  });691  callbacks.push(() => {692    rejectSetMediaKeys = false;693    test('Unable to create or initialize key session', 'third promise fails');694  });695  test('setServerCertificate failed', 'first promise fails');696});697QUnit.test('getLicense not called for messageType that isnt license-request or license-renewal', function(assert) {698  const done = assert.async();699  let getLicenseCalls = 0;700  const options = {701    keySystems: {702      'com.widevine.alpha': {703        url: 'some-url',704        getLicense(emeOptions, keyMessage, callback) {705          getLicenseCalls++;706        }707      }708    }709  };710  const keySystemAccess = {711    keySystem: 'com.widevine.alpha',712    createMediaKeys: () => {713      return Promise.resolve({714        setServerCertificate: () => Promise.resolve(),715        createSession: () => {716          return {717            addEventListener: (event, callback) => {718              if (event === 'message') {719                setTimeout(() => {720                  callback({message: 'whatever', messageType: 'do-not-request-license'});721                  assert.equal(getLicenseCalls, 0, 'did not call getLicense');722                  done();723                });724              }725            },726            keyStatuses: [],727            generateRequest: () => Promise.resolve()728          };729        }730      });731    }732  };733  const video = {734    setMediaKeys: () => Promise.resolve()735  };736  standard5July2016({737    video,738    keySystemAccess,739    options,740    eventBus: getMockEventBus()741  });742});743QUnit.test('getLicense promise rejection', function(assert) {744  const options = {745    keySystems: {746      'com.widevine.alpha': {747        url: 'some-url',748        getLicense(emeOptions, keyMessage, callback) {749          callback('error getting license');750        }751      }752    }753  };754  const keySystemAccess = {755    keySystem: 'com.widevine.alpha',756    createMediaKeys: () => {757      return Promise.resolve({758        setServerCertificate: () => Promise.resolve(),759        createSession: () => {760          return {761            addEventListener: (event, callback) => {762              setTimeout(() => {763                callback({message: 'whatever', messageType: 'license-request'});764              });765            },766            keyStatuses: [],767            generateRequest: () => Promise.resolve()768          };769        }770      });771    }772  };773  const video = {774    setMediaKeys: () => Promise.resolve()775  };776  const done = assert.async(1);777  standard5July2016({778    video,779    keySystemAccess,780    options,781    eventBus: getMockEventBus()782  }).catch((err) => {783    assert.equal(err, 'error getting license', 'correct error message');784    done();785  });786});787QUnit.test('getLicense calls back with error for 400 and 500 status codes', function(assert) {788  const getLicenseCallback = sinon.spy();789  const getLicense = defaultGetLicense({});790  function toArrayBuffer(obj) {791    const json = JSON.stringify(obj);792    const buffer = new ArrayBuffer(json.length);793    const bufferView = new Uint8Array(buffer);794    for (let i = 0; i < json.length; i++) {795      bufferView[i] = json.charCodeAt(i);796    }797    return buffer;798  }799  videojs.xhr = (params, callback) => {800    return callback(null, {statusCode: 400}, toArrayBuffer({body: 'some-body'}));801  };802  getLicense({}, null, getLicenseCallback);803  videojs.xhr = (params, callback) => {804    return callback(null, {statusCode: 500}, toArrayBuffer({body: 'some-body'}));805  };806  getLicense({}, null, getLicenseCallback);807  videojs.xhr = (params, callback) => {808    return callback(null, {statusCode: 599}, toArrayBuffer({body: 'some-body'}));809  };810  getLicense({}, null, getLicenseCallback);811  assert.equal(getLicenseCallback.callCount, 3, 'correct callcount');812  assert.ok(getLicenseCallback.alwaysCalledWith({813    cause: JSON.stringify({body: 'some-body'})814  }), 'getLicense callback called with correct error');815});816QUnit.test('getLicense calls back with response body for non-400/500 status codes', function(assert) {817  const getLicenseCallback = sinon.spy();818  const getLicense = defaultGetLicense({});819  videojs.xhr = (params, callback) => {820    return callback(null, {statusCode: 200}, {body: 'some-body'});821  };822  getLicense({}, null, getLicenseCallback);823  videojs.xhr = (params, callback) => {824    return callback(null, {statusCode: 399}, {body: 'some-body'});825  };826  getLicense({}, null, getLicenseCallback);827  videojs.xhr = (params, callback) => {828    return callback(null, {statusCode: 600}, {body: 'some-body'});829  };830  getLicense({}, null, getLicenseCallback);831  assert.equal(getLicenseCallback.callCount, 3, 'correct callcount');832  assert.equal(getLicenseCallback.alwaysCalledWith(null, {body: 'some-body'}), true, 'getLicense callback called with correct args');833});834QUnit.test('keySession.update promise rejection', function(assert) {835  const options = {836    keySystems: {837      'com.widevine.alpha': {838        url: 'some-url',839        getLicense(emeOptions, keyMessage, callback) {840          callback(null, 'license');841        }842      }843    }844  };845  const keySystemAccess = {846    keySystem: 'com.widevine.alpha',847    createMediaKeys: () => {848      return Promise.resolve({849        setServerCertificate: () => Promise.resolve(),850        createSession: () => {851          return {852            addEventListener: (event, callback) => {853              setTimeout(() => {854                callback({messageType: 'license-request', message: 'whatever'});855              });856            },857            keyStatuses: [],858            generateRequest: () => Promise.resolve(),859            update: () => Promise.reject('keySession update failed')860          };861        }862      });863    }864  };865  const video = {866    setMediaKeys: () => Promise.resolve()867  };868  const done = assert.async(1);869  standard5July2016({870    video,871    keySystemAccess,872    options,873    eventBus: getMockEventBus()874  }).catch((err) => {875    assert.equal(err, 'keySession update failed', 'correct error message');876    done();877  });878});879QUnit.test('emeHeaders option sets headers on default license xhr request', function(assert) {880  const done = assert.async();881  const origXhr = videojs.xhr;882  const xhrCalls = [];883  const session = new videojs.EventTarget();884  videojs.xhr = (options) => {885    xhrCalls.push(options);886  };887  const keySystemAccess = {888    keySystem: 'com.widevine.alpha',889    createMediaKeys: () => {890      return {891        createSession: () => session892      };893    }894  };895  standard5July2016({896    keySystemAccess,897    video: {898      setMediaKeys: (createdMediaKeys) => Promise.resolve(createdMediaKeys)899    },900    initDataType: '',901    initData: '',902    options: {903      keySystems: {904        'com.widevine.alpha': 'some-url'905      },906      emeHeaders: {907        'Some-Header': 'some-header-value'908      }909    },910    eventBus: getMockEventBus()911  }).catch((e) => {});912  setTimeout(() => {913    session.trigger({914      type: 'message',915      message: 'the-message',916      messageType: 'license-request'917    });918    assert.equal(xhrCalls.length, 1, 'made one XHR');919    assert.deepEqual(xhrCalls[0], {920      uri: 'some-url',921      method: 'POST',922      responseType: 'arraybuffer',923      body: 'the-message',924      headers: {925        'Content-type': 'application/octet-stream',926        'Some-Header': 'some-header-value'927      }928    }, 'made request with proper emeHeaders option value');929    videojs.xhr = origXhr;930    done();931  });932});933QUnit.test('licenseHeaders keySystems property overrides emeHeaders value', function(assert) {934  const done = assert.async();935  const origXhr = videojs.xhr;936  const xhrCalls = [];937  const session = new videojs.EventTarget();938  videojs.xhr = (options) => {939    xhrCalls.push(options);940  };941  const keySystemAccess = {942    keySystem: 'com.widevine.alpha',943    createMediaKeys: () => {944      return {945        createSession: () => session946      };947    }948  };949  standard5July2016({950    keySystemAccess,951    video: {952      setMediaKeys: (createdMediaKeys) => Promise.resolve(createdMediaKeys)953    },954    initDataType: '',955    initData: '',956    options: {957      keySystems: {958        'com.widevine.alpha': {959          url: 'some-url',960          licenseHeaders: {961            'Some-Header': 'priority-header-value'962          }963        }964      },965      emeHeaders: {966        'Some-Header': 'lower-priority-header-value'967      }968    },969    eventBus: getMockEventBus()970  }).catch((e) => {});971  setTimeout(() => {972    session.trigger({973      type: 'message',974      message: 'the-message',975      messageType: 'license-request'976    });977    assert.equal(xhrCalls.length, 1, 'made one XHR');978    assert.deepEqual(xhrCalls[0], {979      uri: 'some-url',980      method: 'POST',981      responseType: 'arraybuffer',982      body: 'the-message',983      headers: {984        'Content-type': 'application/octet-stream',985        'Some-Header': 'priority-header-value'986      }987    }, 'made request with proper licenseHeaders value');988    videojs.xhr = origXhr;989    done();990  });991});992QUnit.test('sets required fairplay defaults if not explicitly configured', function(assert) {993  const origRequestMediaKeySystemAccess = window.navigator.requestMediaKeySystemAccess;994  window.navigator.requestMediaKeySystemAccess = (keySystem, systemOptions) => {995    assert.ok(996      systemOptions[0].initDataTypes.indexOf('sinf') !== -1,997      'includes required initDataType'998    );999    assert.ok(1000      systemOptions[0].videoCapabilities[0].contentType.indexOf('video/mp4') !== -1,1001      'includes required video contentType'1002    );1003  };1004  getSupportedKeySystem({'com.apple.fps': {}});1005  window.requestMediaKeySystemAccess = origRequestMediaKeySystemAccess;1006});1007QUnit.module('session management');1008QUnit.test('addSession saves options', function(assert) {1009  const video = {1010    pendingSessionData: []1011  };1012  const initDataType = 'temporary';1013  const initData = new Uint8Array();1014  const options = { some: 'option' };1015  const getLicense = () => '';1016  const removeSession = () => '';1017  const eventBus = { trigger: () => {} };1018  const contentId = null;...plugin.js
Source:plugin.js  
...47    // return silently since it may be handled by a different system48    return Promise.resolve();49  }50  let initData = event.initData;51  return getSupportedKeySystem(options.keySystems).then((keySystemAccess) => {52    const keySystem = keySystemAccess.keySystem;53    // Use existing init data from options if provided54    if (options.keySystems[keySystem] &&55        options.keySystems[keySystem].pssh) {56      initData = options.keySystems[keySystem].pssh;57    }58    // "Initialization Data must be a fixed value for a given set of stream(s) or media59    // data. It must only contain information related to the keys required to play a given60    // set of stream(s) or media data."61    // eslint-disable-next-line max-len62    // @see [Initialization Data Spec]{@link https://www.w3.org/TR/encrypted-media/#initialization-data}63    if (hasSession(sessions, initData) || !initData) {64      // TODO convert to videojs.log.debug and add back in65      // https://github.com/videojs/video.js/pull/4780...Using AI Code Generation
1var config = [{2    audioCapabilities: [{3        contentType: 'audio/mp4; codecs="mp4a.40.2"'4    }],5    videoCapabilities: [{6        contentType: 'video/mp4; codecs="avc1.4d401e"'7    }]8}];9navigator.requestMediaKeySystemAccess('com.widevine.alpha', config)10.then(function(access) {11    return access.createMediaKeys();12})13.then(function(keys) {14    console.log('MediaKeys created');15})16.catch(function(error) {17    console.log('Error: ' + error);18});19var keySystem = 'com.widevine.alpha';20var config = [{21    audioCapabilities: [{22        contentType: 'audio/mp4; codecs="mp4a.40.2"'23    }],24    videoCapabilities: [{25        contentType: 'video/mp4; codecs="avc1.4d401e"'26    }]27}];28navigator.requestMediaKeySystemAccess(keySystem, config)29.then(function(access) {30    console.log('MediaKeySystemAccess created');31    return access.createMediaKeys();32})33.then(function(keys) {34    console.log('MediaKeys created');35})36.catch(function(error) {37    console.log('Error: ' + error);38});39var keySystem = 'com.microsoft.playready';40var config = [{41    audioCapabilities: [{42        contentType: 'audio/mp4; codecs="mp4a.40.2"'43    }],44    videoCapabilities: [{45        contentType: 'video/mp4; codecs="avc1.4d401e"'46    }]47}];48navigator.requestMediaKeySystemAccess(keySystem, config)49.then(function(access) {50    console.log('MediaKeySystemAccess created');51    return access.createMediaKeys();52})53.then(function(keys) {54    console.log('MediaKeys created');55})56.catch(function(error) {57    console.log('Error: ' + error);58});Using AI Code Generation
1const video = document.createElement("video");2const keySystem = "com.widevine.alpha";3const keySystemConfig = {4  videoCapabilities: [{ contentType: "video/webm; codecs=\"vp9\"" }],5  audioCapabilities: [{ contentType: "audio/webm; codecs=\"opus\"" }],6};7if (video.getSupportedKeySystem) {8  const supported = video.getSupportedKeySystem(keySystem, keySystemConfig);9  console.log("getSupportedKeySystem result: " + supported);10} else {11  console.log("getSupportedKeySystem not supported");12}Using AI Code Generation
1var wptbem = require('wptbem');2var supportedKeySystem = wptbem.getSupportedKeySystem();3console.log(supportedKeySystem);4var supportedKeySystem = "com.widevine.alpha";5var video = document.getElementById('video');6var videoSource = document.getElementById('videoSource');7var mediaKeys;8var mediaKeySession;9var keyMessage;10video = document.createElement('video');11video.id = 'video';12video.width = 1280;13video.height = 720;14video.autoplay = true;15video.controls = true;16videoSource = document.createElement('source');17videoSource.id = 'videoSource';18videoSource.type = 'application/dash+xml';19video.appendChild(videoSource);20document.body.appendChild(video);21video.addEventListener('encrypted', function (event) {22    keyMessage = event.initData;23    console.log("Encrypted Event");24    console.log("initData: " + event.initData);25    console.log("initDataType: " + event.initDataType);26});27video.addEventListener('canplay', function () {28    console.log("Can Play Event");29    navigator.requestMediaKeySystemAccess(supportedKeySystem, [{Using AI Code Generation
1var keySystem = wptb.getSupportedKeySystem('com.widevine.alpha');2if (keySystem)3  console.log("Key System is supported: " + keySystem);4  console.log("Key System is not supported");5var keySystem = wptb.getSupportedKeySystem('org.w3.clearkey');6if (keySystem)7  console.log("Key System is supported: " + keySystem);8  console.log("Key System is not supported");Using AI Code Generation
1var wptRunner = new WptRunner();2wptRunner.getSupportedKeySystem('com.widevine.alpha', function (supported) {3  console.log('supported: ' + supported);4});5var WptRunner = function () {6  this.getSupportedKeySystem = function (keySystem, callback) {7    var supported = false;8    try {9      var keySystemAccess = navigator.requestMediaKeySystemAccess(keySystem, [{10        videoCapabilities: [{11          contentType: 'video/mp4; codecs="avc1.42E01E"'12        }]13      }]);14      supported = true;15    } catch (e) {16      supported = false;17    }18    callback(supported);19  };20};21var wptRunner = new WptRunner();22wptRunner.getSupportedKeySystem('com.widevine.alpha', function (supported) {23  console.log('supported: ' + supported);24});25var WptRunner = function () {26  this.getSupportedKeySystem = function (keySystem, callback) {27    var supported = false;28    try {29      var keySystemAccess = navigator.requestMediaKeySystemAccess(keySystem, [{30        videoCapabilities: [{31          contentType: 'video/mp4; codecs="avc1.42E01E"'32        }]33      }]);34      supported = true;35    } catch (e) {36      supported = false;37    }38    callback(supported);39  };40};41var WptRunner = function () {42  this.getSupportedKeySystem = function (keySystem, callback) {43    var supported = false;Using AI Code Generation
1var config = {2  audioCapabilities: [{3    contentType: 'audio/mp4; codecs="mp4a.40.2"'4  }],5  videoCapabilities: [{6    contentType: 'video/mp4; codecs="avc1.4d400d"'7  }],8};9navigator.requestMediaKeySystemAccess('com.widevine.alpha', [config]).then(function(access) {10  console.log('Widevine is supported');11}, function() {12  console.log('Widevine is not supported');13});Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
