Best JavaScript code snippet using ava
redisWorker.spec.js
Source:redisWorker.spec.js
1/**2 * @jest-environment node3 */4// Redis Worker Tests5jest.setTimeout(60000);6const { coordinator, readStore } = require('../models/redisWorker');7const { v4 : uuidv4 } = require('uuid');8const shajs = require("sha.js");9const hash = (obj) => {10 obj = obj.toString();11 return shajs('sha256').update(obj).digest('hex');12}13let worker = new coordinator();14describe("Basic Redis Worker tests", () => {15 let key = uuidv4();16 test("should be able to write/read data", async () => {17 let value = "Hello, World!"18 await worker.set(key, value);19 expect(await worker.get(key)).toBe(value);20 });21 test("should be able to delete data", async () => {22 await worker.del(key);23 expect(await worker.get(key)).toBeFalsy();24 });25 test("should be able to find patterned keys", async () => {26 let suffixes = ["cat", "dog", "hen"];27 let patterned_key;28 for (const suffix of suffixes){29 patterned_key = `${key}_${suffix}`;30 await worker.set(patterned_key, suffix);31 }32 let matches = await worker.keys(`${key}*`);33 expect(await matches.length).toBe(suffixes.length);34 });35});36describe("Coordinator tests - Spin up", () => {37 let targetPrefix = "myTestJob"38 let runner = "python"39 let callable = "dummy.py"40 test("should be able to spin up a processor worker", async () => {41 let agentType = "proc"42 await worker.spinUp(agentType, targetPrefix, runner, callable);43 let store = readStore();44 let sessionKey = hash(`${agentType}_${targetPrefix}_${runner}_${callable}`);45 expect(store[sessionKey]).toBeTruthy();46 });47 test("should be able to spin up an aggregator worker", async () => {48 let agentType = "agg"49 await worker.spinUp(agentType, targetPrefix, runner, callable);50 let store = readStore();51 let sessionKey = hash(`${agentType}_${targetPrefix}_${runner}_${callable}`);52 expect(store[sessionKey]).toBeTruthy();53 });54});55describe("Coordinator tests - Tear down", () => {56 let targetPrefix = "myTestJob"57 let runner = "python"58 let callable = "dummy.py"59 test("should be able to tear down processor workers", async () => {60 let agentType = "proc"61 worker.tearDown(agentType, targetPrefix, runner, callable);62 await worker.updatePIDs(agentType, targetPrefix, runner, callable);63 let new_pids = worker.getPIDs(agentType, targetPrefix, runner, callable);64 expect(new_pids.length).toBe(0);65 });66 test("should be able to tear down aggregator workers", async () => {67 let agentType = "agg"68 worker.tearDown(agentType, targetPrefix, runner, callable);69 await worker.updatePIDs(agentType, targetPrefix, runner, callable);70 let new_pids = worker.getPIDs(agentType, targetPrefix, runner, callable);71 expect(new_pids.length).toBe(0);72 });...
plugin.js
Source:plugin.js
1const v8 = require('v8');2const pkg = require('../../package.json');3const subprocess = require('./subprocess');4const options = require('./options');5const workers = new Map();6const workerTeardownFns = new WeakMap();7function createSharedWorker(filename, initialData, teardown) {8 const channel = subprocess.registerSharedWorker(filename, initialData, teardown);9 class ReceivedMessage {10 constructor(id, serializedData) {11 this.id = id;12 this.data = v8.deserialize(new Uint8Array(serializedData));13 }14 reply(data) {15 return publishMessage(data, this.id);16 }17 }18 // Ensure that, no matter how often it's received, we have a stable message19 // object.20 const messageCache = new WeakMap();21 async function * receiveMessages(replyTo) {22 for await (const evt of channel.receive()) {23 if (replyTo === undefined && evt.replyTo !== undefined) {24 continue;25 }26 if (replyTo !== undefined && evt.replyTo !== replyTo) {27 continue;28 }29 let message = messageCache.get(evt);30 if (message === undefined) {31 message = new ReceivedMessage(evt.messageId, evt.serializedData);32 messageCache.set(evt, message);33 }34 yield message;35 }36 }37 function publishMessage(data, replyTo) {38 const id = channel.post([...v8.serialize(data)], replyTo);39 return {40 id,41 async * replies() {42 yield * receiveMessages(id);43 }44 };45 }46 return {47 available: channel.available,48 protocol: 'experimental',49 get currentlyAvailable() {50 return channel.currentlyAvailable;51 },52 publish(data) {53 return publishMessage(data);54 },55 async * subscribe() {56 yield * receiveMessages();57 }58 };59}60function registerSharedWorker({61 filename,62 initialData,63 supportedProtocols,64 teardown65}) {66 if (!options.get().experiments.sharedWorkers) {67 throw new Error('Shared workers are experimental. Opt in to them in your AVA configuration');68 }69 if (!supportedProtocols.includes('experimental')) {70 throw new Error(`This version of AVA (${pkg.version}) does not support any of the desired shared worker protocols: ${supportedProtocols.join()}`);71 }72 let worker = workers.get(filename);73 if (worker === undefined) {74 worker = createSharedWorker(filename, initialData, async () => {75 // Run possibly asynchronous teardown functions serially, in reverse76 // order. Any error will crash the worker.77 const teardownFns = workerTeardownFns.get(worker);78 if (teardownFns !== undefined) {79 for await (const fn of [...teardownFns].reverse()) {80 await fn();81 }82 }83 });84 workers.set(filename, worker);85 }86 if (teardown !== undefined) {87 if (workerTeardownFns.has(worker)) {88 workerTeardownFns.get(worker).push(teardown);89 } else {90 workerTeardownFns.set(worker, [teardown]);91 }92 }93 return worker;94}...
_worker.js
Source:_worker.js
1module.exports = async ({negotiateProtocol}) => {2 const protocol = negotiateProtocol(['experimental']);3 // When we're ready to receive workers or messages.4 protocol.ready();5 // Calling it twice is harmless.6 protocol.ready();7 echo(protocol.subscribe());8 handleWorkers(protocol);9};10const handled = new WeakSet();11async function echo(messages) {12 for await (const message of messages) {13 if (!handled.has(message)) {14 handled.add(message);15 echo(message.reply(message.data).replies());16 }17 }18}19async function handleWorkers(protocol) {20 for await (const testWorker of protocol.testWorkers()) {21 testWorker.teardown(() => {22 protocol.broadcast({cleanup: testWorker.file});23 });24 let byeCount = 0;25 const bye = testWorker.teardown(() => {26 byeCount++;27 setImmediate(() => {28 protocol.broadcast({bye: testWorker.file, byeCount});29 });30 });31 testWorker.publish({hello: testWorker.file});32 echo(protocol.broadcast({broadcast: testWorker.file}).replies());33 echo(testWorker.subscribe());34 for await (const message of testWorker.subscribe()) {35 if (message.data === 'ð') {36 bye();37 bye(); // Second call is a no-op.38 break;39 }40 }41 }...
Using AI Code Generation
1import test from 'ava';2import { Worker } from 'worker_threads';3test('foo', t => {4 const worker = new Worker('./worker.js');5 t.teardown(() => worker.terminate());6});7import { parentPort } from 'worker_threads';8parentPort.on('message', message => {9 if (message === 'terminate') {10 parentPort.postMessage('terminated');11 }12});13MIT © [Jagadish Chakravarthi](
Using AI Code Generation
1import test from 'ava';2import worker from 'worker_threads';3test('my test', t => {4 t.pass();5 worker.teardown();6});7import test from 'ava';8import worker from 'worker_threads';9test('my test', t => {10 t.pass();11 worker.teardown();12});13### worker.teardown()14MIT © [Rishabh Anand](
Using AI Code Generation
1const test = require('ava');2const worker = require('./worker');3test('worker.teardown', async t => {4 await worker.teardown();5 t.pass();6});7### `worker.teardown()`8### `worker.kill()`9### `worker.send(message)`10Sends a message to the worker process. The message will be serialized using [`serialize-javascript`](
Using AI Code Generation
1const test = require('ava');2const worker = require('ava/worker/child');3test('test', t => {4 t.pass();5});6worker.teardown();7### `worker.teardown()`
Using AI Code Generation
1const test = require('ava');2const worker = require('ava/worker');3test('test', async t => {4 const { teardown } = worker.setup();5 await teardown();6});7### worker.setup()8### teardown()
Using AI Code Generation
1import test from 'ava'2import { Worker } from 'worker_threads'3test('my test', async t => {4 const worker = new Worker('./worker.js')5 await worker.teardown()6})7import { parentPort } from 'worker_threads'8parentPort.on('message', message => {9})10### `worker.terminate()`11### `worker.getStdout()`12### `worker.getStderr()`13### `worker.unref()`14### `worker.ref()`15- [workerpool](
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!!