Best JavaScript code snippet using wpt
generic-sensor-tests.js
Source:generic-sensor-tests.js
1'use strict';2// Run a set of tests for a given |sensorName|.3// |readingData| is an object with 3 keys, all of which are arrays of arrays:4// 1. "readings". Each value corresponds to one raw reading that will be5// processed by a sensor.6// 2. "expectedReadings". Each value corresponds to the processed value a7// sensor will make available to users (i.e. a capped or rounded value).8// Its length must match |readings|'.9// 3. "expectedRemappedReadings" (optional). Similar to |expectedReadings|, but10// used only by spatial sensors, whose reference frame can change the values11// returned by a sensor.12// Its length should match |readings|'.13// |verificationFunction| is called to verify that a given reading matches a14// value in |expectedReadings|.15// |featurePolicies| represents |sensorName|'s associated sensor feature name.16function runGenericSensorTests(sensorName,17 readingData,18 verificationFunction,19 featurePolicies) {20 const sensorType = self[sensorName];21 function validateReadingFormat(data) {22 return Array.isArray(data) && data.every(element => Array.isArray(element));23 }24 const { readings, expectedReadings, expectedRemappedReadings } = readingData;25 if (!validateReadingFormat(readings)) {26 throw new TypeError('readingData.readings must be an array of arrays.');27 }28 if (!validateReadingFormat(expectedReadings)) {29 throw new TypeError('readingData.expectedReadings must be an array of ' +30 'arrays.');31 }32 if (readings.length != expectedReadings.length) {33 throw new TypeError('readingData.readings and ' +34 'readingData.expectedReadings must have the same ' +35 'length.');36 }37 if (expectedRemappedReadings &&38 !validateReadingFormat(expectedRemappedReadings)) {39 throw new TypeError('readingData.expectedRemappedReadings must be an ' +40 'array of arrays.');41 }42 if (expectedRemappedReadings &&43 readings.length != expectedRemappedReadings.length) {44 throw new TypeError('readingData.readings and ' +45 'readingData.expectedRemappedReadings must have the same ' +46 'length.');47 }48 sensor_test(async (t, sensorProvider) => {49 assert_implements(sensorName in self, `${sensorName} is not supported.`);50 sensorProvider.setGetSensorShouldFail(sensorName, true);51 const sensor = new sensorType;52 const sensorWatcher = new EventWatcher(t, sensor, ["reading", "error"]);53 sensor.start();54 const event = await sensorWatcher.wait_for("error");55 assert_false(sensor.activated);56 assert_equals(event.error.name, 'NotReadableError');57 }, `${sensorName}: Test that onerror is sent when sensor is not supported.`);58 sensor_test(async (t, sensorProvider) => {59 assert_implements(sensorName in self, `${sensorName} is not supported.`);60 sensorProvider.setPermissionsDenied(sensorName, true);61 const sensor = new sensorType;62 const sensorWatcher = new EventWatcher(t, sensor, ["reading", "error"]);63 sensor.start();64 const event = await sensorWatcher.wait_for("error");65 assert_false(sensor.activated);66 assert_equals(event.error.name, 'NotAllowedError');67 }, `${sensorName}: Test that onerror is sent when permissions are not\68 granted.`);69 sensor_test(async (t, sensorProvider) => {70 assert_implements(sensorName in self, `${sensorName} is not supported.`);71 const sensor = new sensorType({frequency: 560});72 const sensorWatcher = new EventWatcher(t, sensor, ["reading", "error"]);73 sensor.start();74 const mockSensor = await sensorProvider.getCreatedSensor(sensorName);75 mockSensor.setStartShouldFail(true);76 const event = await sensorWatcher.wait_for("error");77 assert_false(sensor.activated);78 assert_equals(event.error.name, 'NotReadableError');79 }, `${sensorName}: Test that onerror is send when start() call has failed.`);80 sensor_test(async (t, sensorProvider) => {81 assert_implements(sensorName in self, `${sensorName} is not supported.`);82 const sensor = new sensorType({frequency: 560});83 const sensorWatcher = new EventWatcher(t, sensor, ["activate", "error"]);84 sensor.start();85 const mockSensor = await sensorProvider.getCreatedSensor(sensorName);86 await sensorWatcher.wait_for("activate");87 assert_less_than_equal(mockSensor.getSamplingFrequency(), 60);88 sensor.stop();89 assert_false(sensor.activated);90 }, `${sensorName}: Test that frequency is capped to allowed maximum.`);91 sensor_test(async (t, sensorProvider) => {92 assert_implements(sensorName in self, `${sensorName} is not supported.`);93 const maxSupportedFrequency = 5;94 sensorProvider.setMaximumSupportedFrequency(maxSupportedFrequency);95 const sensor = new sensorType({frequency: 50});96 const sensorWatcher = new EventWatcher(t, sensor, ["activate", "error"]);97 sensor.start();98 const mockSensor = await sensorProvider.getCreatedSensor(sensorName);99 await sensorWatcher.wait_for("activate");100 assert_equals(mockSensor.getSamplingFrequency(), maxSupportedFrequency);101 sensor.stop();102 assert_false(sensor.activated);103 }, `${sensorName}: Test that frequency is capped to the maximum supported\104 frequency.`);105 sensor_test(async (t, sensorProvider) => {106 assert_implements(sensorName in self, `${sensorName} is not supported.`);107 const minSupportedFrequency = 2;108 sensorProvider.setMinimumSupportedFrequency(minSupportedFrequency);109 const sensor = new sensorType({frequency: -1});110 const sensorWatcher = new EventWatcher(t, sensor, ["activate", "error"]);111 sensor.start();112 const mockSensor = await sensorProvider.getCreatedSensor(sensorName);113 await sensorWatcher.wait_for("activate");114 assert_equals(mockSensor.getSamplingFrequency(), minSupportedFrequency);115 sensor.stop();116 assert_false(sensor.activated);117 }, `${sensorName}: Test that frequency is limited to the minimum supported\118 frequency.`);119 promise_test(async t => {120 assert_implements(sensorName in self, `${sensorName} is not supported.`);121 const iframe = document.createElement('iframe');122 iframe.allow = featurePolicies.join(' \'none\'; ') + ' \'none\';';123 iframe.srcdoc = '<script>' +124 ' window.onmessage = message => {' +125 ' if (message.data === "LOADED") {' +126 ' try {' +127 ' new ' + sensorName + '();' +128 ' parent.postMessage("FAIL", "*");' +129 ' } catch (e) {' +130 ' parent.postMessage("PASS", "*");' +131 ' }' +132 ' }' +133 ' };' +134 '<\/script>';135 const iframeWatcher = new EventWatcher(t, iframe, "load");136 document.body.appendChild(iframe);137 await iframeWatcher.wait_for("load");138 iframe.contentWindow.postMessage('LOADED', '*');139 const windowWatcher = new EventWatcher(t, window, "message");140 const message = await windowWatcher.wait_for("message");141 assert_equals(message.data, 'PASS');142 }, `${sensorName}: Test that sensor cannot be constructed within iframe\143 disallowed to use feature policy.`);144 promise_test(async t => {145 assert_implements(sensorName in self, `${sensorName} is not supported.`);146 const iframe = document.createElement('iframe');147 iframe.allow = featurePolicies.join(';') + ';';148 iframe.srcdoc = '<script>' +149 ' window.onmessage = message => {' +150 ' if (message.data === "LOADED") {' +151 ' try {' +152 ' new ' + sensorName + '();' +153 ' parent.postMessage("PASS", "*");' +154 ' } catch (e) {' +155 ' parent.postMessage("FAIL", "*");' +156 ' }' +157 ' }' +158 ' };' +159 '<\/script>';160 const iframeWatcher = new EventWatcher(t, iframe, "load");161 document.body.appendChild(iframe);162 await iframeWatcher.wait_for("load");163 iframe.contentWindow.postMessage('LOADED', '*');164 const windowWatcher = new EventWatcher(t, window, "message");165 const message = await windowWatcher.wait_for("message");166 assert_equals(message.data, 'PASS');167 }, `${sensorName}: Test that sensor can be constructed within an iframe\168 allowed to use feature policy.`);169 sensor_test(async (t, sensorProvider) => {170 assert_implements(sensorName in self, `${sensorName} is not supported.`);171 const sensor = new sensorType();172 const sensorWatcher = new EventWatcher(t, sensor, ["reading", "error"]);173 sensor.start();174 assert_false(sensor.hasReading);175 const mockSensor = await sensorProvider.getCreatedSensor(sensorName);176 await mockSensor.setSensorReading(readings);177 await sensorWatcher.wait_for("reading");178 const expected = new RingBuffer(expectedReadings).next().value;179 assert_true(verificationFunction(expected, sensor));180 assert_true(sensor.hasReading);181 sensor.stop();182 assert_true(verificationFunction(expected, sensor, /*isNull=*/true));183 assert_false(sensor.hasReading);184 }, `${sensorName}: Test that 'onreading' is called and sensor reading is\185 valid.`);186 sensor_test(async (t, sensorProvider) => {187 assert_implements(sensorName in self, `${sensorName} is not supported.`);188 const sensor1 = new sensorType();189 const sensorWatcher1 = new EventWatcher(t, sensor1, ["reading", "error"]);190 sensor1.start();191 const sensor2 = new sensorType();192 const sensorWatcher2 = new EventWatcher(t, sensor2, ["reading", "error"]);193 sensor2.start();194 const mockSensor = await sensorProvider.getCreatedSensor(sensorName);195 await mockSensor.setSensorReading(readings);196 await Promise.all([sensorWatcher1.wait_for("reading"),197 sensorWatcher2.wait_for("reading")]);198 const expected = new RingBuffer(expectedReadings).next().value;199 // Reading values are correct for both sensors.200 assert_true(verificationFunction(expected, sensor1));201 assert_true(verificationFunction(expected, sensor2));202 // After first sensor stops its reading values are null,203 // reading values for the second sensor sensor remain.204 sensor1.stop();205 assert_true(verificationFunction(expected, sensor1, /*isNull=*/true));206 assert_true(verificationFunction(expected, sensor2));207 sensor2.stop();208 assert_true(verificationFunction(expected, sensor2, /*isNull=*/true));209 }, `${sensorName}: sensor reading is correct.`);210 sensor_test(async (t, sensorProvider) => {211 assert_implements(sensorName in self, `${sensorName} is not supported.`);212 const sensor = new sensorType();213 const sensorWatcher = new EventWatcher(t, sensor, ["reading", "error"]);214 sensor.start();215 const mockSensor = await sensorProvider.getCreatedSensor(sensorName);216 await mockSensor.setSensorReading(readings);217 await sensorWatcher.wait_for("reading");218 const cachedTimeStamp1 = sensor.timestamp;219 await sensorWatcher.wait_for("reading");220 const cachedTimeStamp2 = sensor.timestamp;221 assert_greater_than(cachedTimeStamp2, cachedTimeStamp1);222 sensor.stop();223 }, `${sensorName}: sensor timestamp is updated when time passes.`);224 sensor_test(async t => {225 assert_implements(sensorName in self, `${sensorName} is not supported.`);226 const sensor = new sensorType();227 const sensorWatcher = new EventWatcher(t, sensor, ["activate", "error"]);228 assert_false(sensor.activated);229 sensor.start();230 assert_false(sensor.activated);231 await sensorWatcher.wait_for("activate");232 assert_true(sensor.activated);233 sensor.stop();234 assert_false(sensor.activated);235 }, `${sensorName}: Test that sensor can be successfully created and its\236 states are correct.`);237 sensor_test(async t => {238 assert_implements(sensorName in self, `${sensorName} is not supported.`);239 const sensor = new sensorType();240 const sensorWatcher = new EventWatcher(t, sensor, ["activate", "error"]);241 sensor.start();242 sensor.start();243 await sensorWatcher.wait_for("activate");244 assert_true(sensor.activated);245 sensor.stop();246 }, `${sensorName}: no exception is thrown when calling start() on already\247 started sensor.`);248 sensor_test(async t => {249 assert_implements(sensorName in self, `${sensorName} is not supported.`);250 const sensor = new sensorType();251 const sensorWatcher = new EventWatcher(t, sensor, ["activate", "error"]);252 sensor.start();253 await sensorWatcher.wait_for("activate");254 sensor.stop();255 sensor.stop();256 assert_false(sensor.activated);257 }, `${sensorName}: no exception is thrown when calling stop() on already\258 stopped sensor.`);259 sensor_test(async (t, sensorProvider) => {260 assert_implements(sensorName in self, `${sensorName} is not supported.`);261 const sensor = new sensorType();262 const sensorWatcher = new EventWatcher(t, sensor, ["reading", "error"]);263 sensor.start();264 const mockSensor = await sensorProvider.getCreatedSensor(sensorName);265 await mockSensor.setSensorReading(readings);266 const expectedBuffer = new RingBuffer(expectedReadings);267 await sensorWatcher.wait_for("reading");268 const expected1 = expectedBuffer.next().value;269 assert_true(sensor.hasReading);270 assert_true(verificationFunction(expected1, sensor));271 const timestamp = sensor.timestamp;272 sensor.stop();273 assert_false(sensor.hasReading);274 sensor.start();275 await sensorWatcher.wait_for("reading");276 assert_true(sensor.hasReading);277 // |readingData| may have a single reading/expectation value, and this278 // is the second reading we are getting. For that case, make sure we279 // also wrap around as if we had the same RingBuffer used in280 // generic_sensor_mocks.js.281 const expected2 = expectedBuffer.next().value;282 assert_true(verificationFunction(expected2, sensor));283 // Make sure that 'timestamp' is already initialized.284 assert_greater_than(timestamp, 0);285 // Check that the reading is updated.286 assert_greater_than(sensor.timestamp, timestamp);287 sensor.stop();288 }, `${sensorName}: Test that fresh reading is fetched on start().`);289// TBD file a WPT issue: visibilityChangeWatcher times out.290// sensor_test(async (t, sensorProvider) => {291// assert_implements(sensorName in self, `${sensorName} is not supported.`);292// const sensor = new sensorType();293// const sensorWatcher = new EventWatcher(t, sensor, ["reading", "error"]);294// const visibilityChangeWatcher = new EventWatcher(t, document,295// "visibilitychange");296// sensor.start();297// const mockSensor = await sensorProvider.getCreatedSensor(sensorName);298// await mockSensor.setSensorReading(readings);299// await sensorWatcher.wait_for("reading");300// const expected = new RingBuffer(expectedReadings).next().value;301// assert_true(verificationFunction(expected, sensor));302// const cachedTimestamp1 = sensor.timestamp;303// const win = window.open('', '_blank');304// await visibilityChangeWatcher.wait_for("visibilitychange");305// const cachedTimestamp2 = sensor.timestamp;306// win.close();307// sensor.stop();308// assert_equals(cachedTimestamp1, cachedTimestamp2);309// }, `${sensorName}: sensor readings can not be fired on the background tab.`);310 sensor_test(async (t, sensorProvider) => {311 assert_implements(sensorName in self, `${sensorName} is not supported.`);312 const fastSensor = new sensorType({ frequency: 60 });313 t.add_cleanup(() => { fastSensor.stop(); });314 let eventWatcher = new EventWatcher(t, fastSensor, "activate");315 fastSensor.start();316 // Wait for |fastSensor| to be activated so that the call to317 // getSamplingFrequency() below works.318 await eventWatcher.wait_for("activate");319 const mockSensor = await sensorProvider.getCreatedSensor(sensorName);320 await mockSensor.setSensorReading(readings);321 // We need |fastSensorFrequency| because 60Hz might be higher than a sensor322 // type's maximum allowed frequency.323 const fastSensorFrequency = mockSensor.getSamplingFrequency();324 const slowSensorFrequency = fastSensorFrequency * 0.25;325 const slowSensor = new sensorType({ frequency: slowSensorFrequency });326 t.add_cleanup(() => { slowSensor.stop(); });327 eventWatcher = new EventWatcher(t, slowSensor, "activate");328 slowSensor.start();329 // Wait for |slowSensor| to be activated before we check if the mock330 // platform sensor's sampling frequency has changed.331 await eventWatcher.wait_for("activate");332 assert_equals(mockSensor.getSamplingFrequency(), fastSensorFrequency);333 // Now stop |fastSensor| and verify that the sampling frequency has dropped334 // to the one |slowSensor| had requested.335 fastSensor.stop();336 return t.step_wait(() => {337 return mockSensor.getSamplingFrequency() === slowSensorFrequency;338 }, "Sampling frequency has dropped to slowSensor's requested frequency");339 }, `${sensorName}: frequency hint works.`);340// Re-enable after https://github.com/w3c/sensors/issues/361 is fixed.341// test(() => {342// assert_throws_dom("NotSupportedError",343// () => { new sensorType({invalid: 1}) });344// assert_throws_dom("NotSupportedError",345// () => { new sensorType({frequency: 60, invalid: 1}) });346// if (!expectedRemappedReadings) {347// assert_throws_dom("NotSupportedError",348// () => { new sensorType({referenceFrame: "screen"}) });349// }350// }, `${sensorName}: throw 'NotSupportedError' for an unsupported sensor\351// option.`);352 test(() => {353 assert_implements(sensorName in self, `${sensorName} is not supported.`);354 const invalidFreqs = [355 "invalid",356 NaN,357 Infinity,358 -Infinity,359 {}360 ];361 invalidFreqs.map(freq => {362 assert_throws_js(TypeError,363 () => { new sensorType({frequency: freq}) },364 `when freq is ${freq}`);365 });366 }, `${sensorName}: throw 'TypeError' if frequency is invalid.`);367 if (!expectedRemappedReadings) {368 // The sensorType does not represent a spatial sensor.369 return;370 }371 sensor_test(async (t, sensorProvider) => {372 assert_implements(sensorName in self, `${sensorName} is not supported.`);373 const sensor1 = new sensorType({frequency: 60});374 const sensor2 = new sensorType({frequency: 60, referenceFrame: "screen"});375 const sensorWatcher1 = new EventWatcher(t, sensor1, ["reading", "error"]);376 const sensorWatcher2 = new EventWatcher(t, sensor1, ["reading", "error"]);377 sensor1.start();378 sensor2.start();379 const mockSensor = await sensorProvider.getCreatedSensor(sensorName);380 await mockSensor.setSensorReading(readings);381 await Promise.all([sensorWatcher1.wait_for("reading"),382 sensorWatcher2.wait_for("reading")]);383 const expected = new RingBuffer(expectedReadings).next().value;384 const expectedRemapped =385 new RingBuffer(expectedRemappedReadings).next().value;386 assert_true(verificationFunction(expected, sensor1));387 assert_true(verificationFunction(expectedRemapped, sensor2));388 sensor1.stop();389 assert_true(verificationFunction(expected, sensor1, /*isNull=*/true));390 assert_true(verificationFunction(expectedRemapped, sensor2));391 sensor2.stop();392 assert_true(verificationFunction(expectedRemapped, sensor2,393 /*isNull=*/true));394 }, `${sensorName}: sensor reading is correct when options.referenceFrame\395 is 'screen'.`);396 test(() => {397 assert_implements(sensorName in self, `${sensorName} is not supported.`);398 const invalidRefFrames = [399 "invalid",400 null,401 123,402 {},403 "",404 true405 ];406 invalidRefFrames.map(refFrame => {407 assert_throws_js(TypeError,408 () => { new sensorType({referenceFrame: refFrame}) },409 `when refFrame is ${refFrame}`);410 });411 }, `${sensorName}: throw 'TypeError' if referenceFrame is not one of\412 enumeration values.`);413}414function runGenericSensorInsecureContext(sensorName) {415 test(() => {416 assert_false(sensorName in window, `${sensorName} must not be exposed`);417 }, `${sensorName} is not exposed in an insecure context.`);...
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!!