How to use workerReply method in Jest

Best JavaScript code snippet using jest

Farm.test.js

Source:Farm.test.js Github

copy

Full Screen

...13}14function workerReplyEnd(i, error, result) {15 mockWorkerCalls[i].onEnd(error, result);16}17function workerReply(i, error, result) {18 workerReplyStart(i);19 workerReplyEnd(i, error, result);20}21function workerReplyCustomMessage(i, message) {22 mockWorkerCalls[i].onCustomMessage(message);23}24describe('Farm', () => {25 beforeEach(() => {26 mockWorkerCalls = [];27 callback = jest.fn((...args) => {28 mockWorkerCalls.push({29 onCustomMessage: args[4],30 onEnd: args[3],31 onStart: args[2],32 passed: args[1],33 workerId: args[0],34 });35 });36 });37 it('sends a request to one worker', () => {38 const farm = new Farm(4, callback);39 farm.doWork('foo', 42);40 expect(callback).toHaveBeenCalledTimes(1);41 expect(callback).toHaveBeenCalledWith(42 0,43 [1, true, 'foo', [42]],44 expect.any(Function),45 expect.any(Function),46 expect.any(Function),47 );48 });49 it('sends four requests to four unique workers', () => {50 const farm = new Farm(4, callback);51 farm.doWork('foo', 42);52 farm.doWork('foo1', 43);53 farm.doWork('foo2', 44);54 farm.doWork('foo3', 45);55 expect(callback).toHaveBeenCalledTimes(4);56 expect(callback).toHaveBeenNthCalledWith(57 1,58 0, // first worker59 [1, true, 'foo', [42]],60 expect.any(Function),61 expect.any(Function),62 expect.any(Function),63 );64 expect(callback).toHaveBeenNthCalledWith(65 2,66 1, // second worker67 [1, true, 'foo1', [43]],68 expect.any(Function),69 expect.any(Function),70 expect.any(Function),71 );72 expect(callback).toHaveBeenNthCalledWith(73 3,74 2, // third worker75 [1, true, 'foo2', [44]],76 expect.any(Function),77 expect.any(Function),78 expect.any(Function),79 );80 expect(callback).toHaveBeenNthCalledWith(81 4,82 3, // fourth worker83 [1, true, 'foo3', [45]],84 expect.any(Function),85 expect.any(Function),86 expect.any(Function),87 );88 });89 it('handles null computeWorkerKey, sending to first worker', async () => {90 const computeWorkerKey = jest.fn(() => null);91 const farm = new Farm(4, callback, computeWorkerKey);92 const p0 = farm.doWork('foo', 42);93 workerReply(0);94 await p0;95 expect(computeWorkerKey).toBeCalledTimes(1);96 expect(computeWorkerKey).toHaveBeenNthCalledWith(1, 'foo', 42);97 expect(callback).toHaveBeenCalledTimes(1);98 expect(callback).toHaveBeenNthCalledWith(99 1,100 0, // first worker101 [1, true, 'foo', [42]],102 expect.any(Function),103 expect.any(Function),104 expect.any(Function),105 );106 });107 it('sends the same worker key to the same worker', async () => {108 const computeWorkerKey = jest109 .fn(() => {})110 .mockReturnValueOnce('one')111 .mockReturnValueOnce('two')112 .mockReturnValueOnce('one');113 const farm = new Farm(4, callback, computeWorkerKey);114 const p0 = farm.doWork('foo', 42);115 workerReply(0);116 await p0;117 const p1 = farm.doWork('foo1', 43);118 workerReply(1);119 await p1;120 const p2 = farm.doWork('foo2', 44);121 workerReply(2);122 await p2;123 expect(computeWorkerKey).toBeCalledTimes(3);124 expect(computeWorkerKey).toHaveBeenNthCalledWith(1, 'foo', 42);125 expect(computeWorkerKey).toHaveBeenNthCalledWith(2, 'foo1', 43);126 expect(computeWorkerKey).toHaveBeenNthCalledWith(3, 'foo2', 44);127 expect(callback).toHaveBeenCalledTimes(3);128 expect(callback).toHaveBeenNthCalledWith(129 1,130 0, // first worker131 [1, true, 'foo', [42]],132 expect.any(Function),133 expect.any(Function),134 expect.any(Function),135 );136 expect(callback).toHaveBeenNthCalledWith(137 2,138 1, // second worker139 [1, true, 'foo1', [43]],140 expect.any(Function),141 expect.any(Function),142 expect.any(Function),143 );144 expect(callback).toHaveBeenNthCalledWith(145 3,146 0, // first worker again147 [1, true, 'foo2', [44]],148 expect.any(Function),149 expect.any(Function),150 expect.any(Function),151 );152 });153 it('returns the result if the call worked', async () => {154 const farm = new Farm(4, callback);155 const promise = farm.doWork('car', 'plane');156 workerReply(0, null, 34);157 const result = await promise;158 expect(result).toEqual(34);159 });160 it('throws if the call failed', async () => {161 const farm = new Farm(4, callback);162 const promise = farm.doWork('car', 'plane');163 let error = null;164 workerReply(0, new TypeError('Massively broken'));165 try {166 await promise;167 } catch (err) {168 error = err;169 }170 expect(error).not.toBe(null);171 expect(error).toBeInstanceOf(TypeError);172 });173 it('checks that once a sticked task finishes, next time is sent to that worker', async () => {174 const farm = new Farm(4, callback, () => '1234567890abcdef');175 // Worker 1 successfully replies with "17" as a result.176 const p0 = farm.doWork('car', 'plane');177 workerReply(0, null, 17);178 await p0;179 // Note that the stickiness is not created by the method name or the180 // arguments it is solely controlled by the provided "computeWorkerKey"181 // method, which in the test example always returns the same key, so all182 // calls should be redirected to worker 1 (which is the one that resolved183 // the first call).184 const p1 = farm.doWork('foo', 'bar');185 workerReply(1, null, 17);186 await p1;187 // The first time, a call with a "1234567890abcdef" hash had never been188 // done earlier ("foo" call), so it got queued to all workers. Later, since189 // the one that resolved the call was the one in position 1, all subsequent190 // calls are only redirected to that worker.191 expect(callback).toHaveBeenCalledTimes(2); // Only "foo".192 expect(callback).toHaveBeenNthCalledWith(193 1,194 0, // first worker195 [1, true, 'car', ['plane']],196 expect.any(Function),197 expect.any(Function),198 expect.any(Function),199 );200 expect(callback).toHaveBeenNthCalledWith(201 2,202 0, // first worker203 [1, true, 'foo', ['bar']],204 expect.any(Function),205 expect.any(Function),206 expect.any(Function),207 );208 });209 it('checks that even before a sticked task finishes, next time is sent to that worker', async () => {210 const farm = new Farm(4, callback, () => '1234567890abcdef');211 // Note that the worker is sending a start response synchronously.212 const p0 = farm.doWork('car', 'plane');213 workerReplyStart(0);214 // Note that the worker is sending a start response synchronously.215 const p1 = farm.doWork('foo', 'bar');216 // The first call is sent the worker, the second is queued217 expect(callback).toHaveBeenCalledTimes(1);218 // Flush the queue219 workerReplyEnd(0, null, 17);220 await p0;221 workerReply(1, null, 17);222 await p1;223 // Both requests are send to the same worker. The first time, a call with224 // a "1234567890abcdef" hash had never been done earlier ("foo" call), so225 // it got queued to all workers. Later, since the one that resolved the226 // call was the one in position 1, all subsequent calls are only redirected227 // to that worker.228 expect(callback).toHaveBeenCalledTimes(2);229 expect(callback).toHaveBeenNthCalledWith(230 1,231 0, // first worker232 [1, true, 'car', ['plane']],233 expect.any(Function),234 expect.any(Function),235 expect.any(Function),236 );237 expect(callback).toHaveBeenNthCalledWith(238 2,239 0, // first worker240 [1, true, 'foo', ['bar']],241 expect.any(Function),242 expect.any(Function),243 expect.any(Function),244 );245 });246 it('checks that locking works, and jobs are never lost', async () => {247 const hash = jest248 .fn()249 // This will go to both queues, but picked by the first worker.250 .mockReturnValueOnce(0)251 // This will go to both queues too, but picked by the second worker.252 .mockReturnValueOnce(1)253 // This will go to worker 0, now only assigned to it.254 .mockReturnValueOnce(0)255 // This will go to worker 1, now only assigned to it.256 .mockReturnValueOnce(1)257 // This will go to both queues too, but will wait, since workers are busy.258 .mockReturnValueOnce(2)259 // This will only go to the first queue.260 .mockReturnValueOnce(0)261 // This will be gone if the queue implementation is wrong.262 .mockReturnValueOnce(0)263 // Push onto the second queue; potentially wiping the earlier job.264 .mockReturnValueOnce(1);265 const farm = new Farm(2, callback, hash);266 // First and second jobs get resolved, so that their hash is sticked to267 // the right worker: worker assignment is performed when workers reply, not268 // when the call is made.269 const p0 = farm.doWork('work-0');270 const p1 = farm.doWork('work-1');271 workerReply(0, null, 'response-0');272 await p0;273 workerReply(1, null, 'response-1');274 await p1;275 // Now we perform the rest of the calls (7 resolves before 5 and 6, since 4276 // is in both queues, and as soon as you resolve 4, 7 will be picked).277 const p2 = farm.doWork('work-2');278 const p3 = farm.doWork('work-3');279 const p4 = farm.doWork('work-4');280 const p5 = farm.doWork('work-5');281 const p6 = farm.doWork('work-6');282 const p7 = farm.doWork('work-7');283 workerReply(2, null, 'response-2');284 await p2;285 workerReply(3, null, 'response-3');286 await p3;287 workerReply(4, null, 'response-4');288 await p4;289 workerReply(5, null, 'response-7');290 await p7;291 workerReply(6, null, 'response-5');292 await p5;293 workerReply(7, null, 'response-6');294 await p6;295 await expect(p0).resolves.toBe('response-0');296 await expect(p1).resolves.toBe('response-1');297 await expect(p2).resolves.toBe('response-2');298 await expect(p3).resolves.toBe('response-3');299 await expect(p4).resolves.toBe('response-4');300 await expect(p5).resolves.toBe('response-5');301 await expect(p6).resolves.toBe('response-6');302 await expect(p7).resolves.toBe('response-7');303 });304 it('can receive custom messages from workers', async () => {305 expect.assertions(2);306 const farm = new Farm(2, callback);307 const p0 = farm.doWork('work-0');308 const p1 = farm.doWork('work-1');309 const unsubscribe = p0.UNSTABLE_onCustomMessage(message => {310 expect(message).toEqual({key: 0, message: 'foo'});311 });312 p1.UNSTABLE_onCustomMessage(message => {313 expect(message).toEqual({key: 1, message: 'bar'});314 });315 workerReplyStart(0);316 workerReplyStart(1);317 workerReplyCustomMessage(0, {key: 0, message: 'foo'});318 workerReplyCustomMessage(1, {key: 1, message: 'bar'});319 unsubscribe();320 // This message will not received because the listener already321 // unsubscribed.322 workerReplyCustomMessage(0, {key: 0, message: 'baz'});323 workerReply(0, null, 17);324 workerReply(1, null, 17);325 await p0;326 await p1;327 });...

Full Screen

Full Screen

71index.test.js

Source:71index.test.js Github

copy

Full Screen

...13}14function workerReplyEnd(i, error, result) {15 mockWorkers[i].send.mock.calls[0][2](error, result);16}17function workerReply(i, error, result) {18 workerReplyStart(i);19 workerReplyEnd(i, error, result);20}21beforeEach(() => {22 mockWorkers = [];23 // The worker mock returns a worker with custom methods, plus it stores them24 // in a global list, so that they can be accessed later. This list is reset in25 // every test.26 jest.mock('../Worker', () => {27 const fakeClass = jest.fn(() => {28 const fakeWorker = {29 getStderr: () => ({once() {}, pipe() {}}),30 getStdout: () => ({once() {}, pipe() {}}),31 send: jest.fn(),32 };33 mockWorkers.push(fakeWorker);34 return fakeWorker;35 });36 return {37 __esModule: true,38 default: fakeClass,39 };40 });41 jest.mock(42 '/fake-worker.js',43 () => ({44 _shouldNotExist1() {},45 methodA() {},46 methodB() {},47 }),48 {virtual: true},49 );50 jest.mock('/fake-worker-with-default-method.js', () => () => {}, {51 virtual: true,52 });53 Worker = require('../Worker').default;54 Farm = require('../index').default;55});56afterEach(() => {57 jest.resetModules();58});59it('exposes the right API', () => {60 const farm = new Farm('/tmp/baz.js', {61 exposedMethods: ['foo', 'bar'],62 numWorkers: 4,63 });64 expect(typeof farm.foo).toBe('function');65 expect(typeof farm.bar).toBe('function');66});67it('breaks if any of the forbidden methods is tried to be exposed', () => {68 expect(69 () => new Farm('/tmp/baz.js', {exposedMethods: ['getStdout']}),70 ).toThrow();71 expect(72 () => new Farm('/tmp/baz.js', {exposedMethods: ['getStderr']}),73 ).toThrow();74 expect(() => new Farm('/tmp/baz.js', {exposedMethods: ['end']})).toThrow();75});76it('works with minimal options', () => {77 // eslint-disable-next-line no-new78 const farm1 = new Farm('/fake-worker.js');79 expect(Worker).toHaveBeenCalledTimes(require('os').cpus().length - 1);80 expect(typeof farm1.methodA).toBe('function');81 expect(typeof farm1.methodB).toBe('function');82 expect(typeof farm1._shouldNotExist).not.toBe('function');83 // eslint-disable-next-line no-new84 const farm2 = new Farm('/fake-worker-with-default-method.js');85 expect(typeof farm2.default).toBe('function');86});87it('tries instantiating workers with the right options', () => {88 // eslint-disable-next-line no-new89 new Farm('/tmp/baz.js', {90 exposedMethods: ['foo', 'bar'],91 forkOptions: {execArgv: []},92 maxRetries: 6,93 numWorkers: 4,94 });95 expect(Worker).toHaveBeenCalledTimes(4);96 expect(Worker.mock.calls[0][0]).toEqual({97 forkOptions: {execArgv: []},98 maxRetries: 6,99 setupArgs: [],100 workerId: 1,101 workerPath: '/tmp/baz.js',102 });103});104it('create multiple workers with unique worker ids', () => {105 // eslint-disable-next-line no-new106 new Farm('/tmp/baz.js', {107 exposedMethods: ['foo', 'bar'],108 forkOptions: {execArgv: []},109 maxRetries: 6,110 numWorkers: 3,111 });112 expect(Worker).toHaveBeenCalledTimes(3);113 expect(Worker.mock.calls[0][0].workerId).toEqual(1);114 expect(Worker.mock.calls[1][0].workerId).toEqual(2);115 expect(Worker.mock.calls[2][0].workerId).toEqual(3);116});117it('makes a non-existing relative worker throw', () => {118 expect(119 () =>120 new Farm('./baz.js', {121 exposedMethods: [],122 numWorkers: 1,123 }),124 ).toThrow();125});126it('aggregates all stdouts and stderrs from all workers', () => {127 const out = [];128 const err = [];129 Worker.mockImplementation(() => ({130 getStderr: () => ({131 once() {},132 pipe(errStream) {133 err.push(errStream);134 },135 }),136 getStdout: () => ({137 once() {},138 pipe(outStream) {139 out.push(outStream);140 },141 }),142 }));143 const farm = new Farm('/tmp/baz.js', {144 exposedMethods: ['foo', 'bar'],145 numWorkers: 2,146 });147 expect(out.length).toBe(2);148 expect(err.length).toBe(2);149 const stdout = jest.fn();150 const stderr = jest.fn();151 farm.getStdout().on('data', stdout);152 farm.getStderr().on('data', stderr);153 out[0].write(Buffer.from('hello'));154 out[1].write(Buffer.from('bye'));155 err[1].write(Buffer.from('house'));156 err[0].write(Buffer.from('tree'));157 expect(stdout.mock.calls[0][0].toString()).toBe('hello');158 expect(stdout.mock.calls[1][0].toString()).toBe('bye');159 expect(stderr.mock.calls[0][0].toString()).toBe('house');160 expect(stderr.mock.calls[1][0].toString()).toBe('tree');161});162it('works when stdout and stderr are not piped to the parent', () => {163 Worker.mockImplementation(() => ({164 getStderr: () => null,165 getStdout: () => null,166 send: () => null,167 }));168 const farm = new Farm('/tmp/baz.js', {169 exposedMethods: ['foo', 'bar'],170 forkOptions: {171 silent: false,172 stdio: 'inherit',173 },174 numWorkers: 2,175 });176 expect(() => farm.foo()).not.toThrow();177 expect(() => farm.bar()).not.toThrow();178});179it('does not let make calls after the farm is ended', () => {180 const farm = new Farm('/tmp/baz.js', {181 exposedMethods: ['foo', 'bar'],182 numWorkers: 4,183 });184 farm.end();185 expect(() => farm.foo()).toThrow();186 expect(() => farm.bar()).toThrow();187});188it('does not let end the farm after it is ended', () => {189 const farm = new Farm('/tmp/baz.js', {190 exposedMethods: ['foo', 'bar'],191 numWorkers: 4,192 });193 farm.end();194 expect(() => farm.end()).toThrow();195});196it('calls "computeWorkerKey" for each of the calls', () => {197 const computeWorkerKey = jest.fn();198 const farm = new Farm('/tmp/baz.js', {199 computeWorkerKey,200 exposedMethods: ['foo', 'bar'],201 numWorkers: 3,202 });203 farm.foo('car', 'plane');204 expect(computeWorkerKey.mock.calls[0]).toEqual(['foo', 'car', 'plane']);205});206it('returns the result if the call worked', async () => {207 const farm = new Farm('/tmp/baz.js', {208 exposedMethods: ['foo', 'bar'],209 numWorkers: 1,210 });211 const promise = farm.foo('car', 'plane');212 workerReply(0, null, 34);213 expect(await promise).toEqual(34);214});215it('throws if the call failed', async () => {216 const farm = new Farm('/tmp/baz.js', {217 exposedMethods: ['foo', 'bar'],218 numWorkers: 1,219 });220 const promise = farm.foo('car', 'plane');221 let error = null;222 workerReply(0, new TypeError('Massively broken'));223 try {224 await promise;225 } catch (err) {226 error = err;227 }228 expect(error).not.toBe(null);229 expect(error).toBeInstanceOf(TypeError);230});231it('sends non-sticked tasks to all workers', () => {232 const farm = new Farm('/tmp/baz.js', {233 exposedMethods: ['foo', 'bar'],234 numWorkers: 3,235 });236 farm.foo('car', 'plane');237 expect(mockWorkers[0].send).toHaveBeenCalledTimes(1);238 expect(mockWorkers[1].send).toHaveBeenCalledTimes(1);239 expect(mockWorkers[2].send).toHaveBeenCalledTimes(1);240});241it('sends first-time sticked tasks to all workers', () => {242 const farm = new Farm('/tmp/baz.js', {243 computeWorkerKey: () => '1234567890abcdef',244 exposedMethods: ['foo', 'bar'],245 numWorkers: 3,246 });247 farm.foo('car', 'plane');248 expect(mockWorkers[0].send).toHaveBeenCalledTimes(1);249 expect(mockWorkers[1].send).toHaveBeenCalledTimes(1);250 expect(mockWorkers[2].send).toHaveBeenCalledTimes(1);251});252it('checks that once a sticked task finishes, next time is sent to that worker', async () => {253 const farm = new Farm('/tmp/baz.js', {254 computeWorkerKey: () => '1234567890abcdef',255 exposedMethods: ['foo', 'bar'],256 numWorkers: 3,257 });258 // Worker 1 successfully replies with "17" as a result.259 farm.foo('car', 'plane');260 workerReply(1, null, 17);261 // Note that the stickiness is not created by the method name or the arguments262 // it is solely controlled by the provided "computeWorkerKey" method, which in263 // the test example always returns the same key, so all calls should be264 // redirected to worker 1 (which is the one that resolved the first call).265 farm.bar();266 // The first time, a call with a "1234567890abcdef" hash had never been done267 // earlier ("foo" call), so it got queued to all workers. Later, since the one268 // that resolved the call was the one in position 1, all subsequent calls are269 // only redirected to that worker.270 expect(mockWorkers[0].send).toHaveBeenCalledTimes(1); // Only "foo".271 expect(mockWorkers[1].send).toHaveBeenCalledTimes(2); // "foo" + "bar".272 expect(mockWorkers[2].send).toHaveBeenCalledTimes(1); // Only "foo".273});274it('checks that even before a sticked task finishes, next time is sent to that worker', async () => {275 const farm = new Farm('/tmp/baz.js', {276 computeWorkerKey: () => '1234567890abcdef',277 exposedMethods: ['foo', 'bar'],278 numWorkers: 3,279 });280 // Call "foo". Not that the worker is sending a start response synchronously.281 farm.foo('car', 'plane');282 workerReplyStart(1);283 // Call "bar". Not that the worker is sending a start response synchronously.284 farm.bar();285 workerReplyStart(1);286 // The first time, a call with a "1234567890abcdef" hash had never been done287 // earlier ("foo" call), so it got queued to all workers. Later, since the one288 // that resolved the call was the one in position 1, all subsequent calls are289 // only redirected to that worker.290 expect(mockWorkers[0].send).toHaveBeenCalledTimes(1); // Only "foo".291 expect(mockWorkers[1].send).toHaveBeenCalledTimes(2); // "foo" + "bar".292 expect(mockWorkers[2].send).toHaveBeenCalledTimes(1); // Only "foo".293});294it('checks that once a non-sticked task finishes, next time is sent to all workers', async () => {295 // Note there is no "computeWorkerKey".296 const farm = new Farm('/tmp/baz.js', {297 exposedMethods: ['foo', 'bar'],298 numWorkers: 3,299 });300 // Worker 1 successfully replies with "17" as a result.301 const promise = farm.foo('car', 'plane');302 workerReply(1, null, 17);303 await promise;304 farm.bar();305 // Since "computeWorkerKey" does not return anything, new jobs are sent again to306 // all existing workers.307 expect(mockWorkers[0].send).toHaveBeenCalledTimes(2);308 expect(mockWorkers[1].send).toHaveBeenCalledTimes(2);309 expect(mockWorkers[2].send).toHaveBeenCalledTimes(2);310});311it('rotates workers when they are idling', async () => {312 let order;313 let promise;314 // Note there is no "computeWorkerKey".315 const farm = new Farm('/tmp/baz.js', {316 exposedMethods: ['foo', 'bar'],317 numWorkers: 3,318 });319 [0, 1, 2].forEach(i => {320 mockWorkers[i].send.mockReset();321 mockWorkers[i].send.mockImplementation(() => order.push(i));322 });323 // First time, the order is 0, 1, 2.324 order = [];325 promise = farm.foo('car', 'plane');326 expect(order).toEqual([0, 1, 2]);327 // Worker 1 successfully replies with "17" as a result.328 workerReply(1, null, 17);329 await promise;330 [0, 1, 2].forEach(i => {331 mockWorkers[i].send.mockReset();332 mockWorkers[i].send.mockImplementation(() => order.push(i));333 });334 // Now, the order is 1, 2, 0 (shifted one).335 order = [];336 promise = farm.foo('car', 'plane');337 expect(order).toEqual([1, 2, 0]);338 // Worker 1 successfully replies again.339 workerReply(1, null, 17);340 await promise;...

Full Screen

Full Screen

index.test.js

Source:index.test.js Github

copy

Full Screen

...7'use strict';8let Farm;9let Worker;10let mockWorkers;11function workerReply(i, error, result) {12 return mockWorkers[i].send.mock.calls[0][1].call(13 mockWorkers[i],14 error,15 result,16 );17}18beforeEach(() => {19 mockWorkers = [];20 // The worker mock returns a worker with custom methods, plus it stores them21 // in a global list, so that they can be accessed later. This list is reset in22 // every test.23 jest.mock('../worker', () => {24 const fakeClass = jest.fn(() => {25 const fakeWorker = {26 getStderr: () => ({once() {}, pipe() {}}),27 getStdout: () => ({once() {}, pipe() {}}),28 send: jest.fn(),29 };30 mockWorkers.push(fakeWorker);31 return fakeWorker;32 });33 return {34 __esModule: true,35 default: fakeClass,36 };37 });38 jest.mock(39 '/fake-worker.js',40 () => {41 return {42 _shouldNotExist1() {},43 methodA() {},44 methodB() {},45 };46 },47 {virtual: true},48 );49 jest.mock(50 '/fake-worker-with-default-method.js',51 () => {52 return () => {};53 },54 {virtual: true},55 );56 Worker = require('../worker').default;57 Farm = require('../index').default;58});59afterEach(() => {60 jest.resetModules();61});62it('exposes the right API', () => {63 const farm = new Farm('/tmp/baz.js', {64 exposedMethods: ['foo', 'bar'],65 numWorkers: 4,66 });67 expect(typeof farm.foo).toBe('function');68 expect(typeof farm.bar).toBe('function');69});70it('breaks if any of the forbidden methods is tried to be exposed', () => {71 expect(72 () => new Farm('/tmp/baz.js', {exposedMethods: ['getStdout']}),73 ).toThrow();74 expect(75 () => new Farm('/tmp/baz.js', {exposedMethods: ['getStderr']}),76 ).toThrow();77 expect(() => new Farm('/tmp/baz.js', {exposedMethods: ['end']})).toThrow();78});79it('works with minimal options', () => {80 // eslint-disable-next-line no-new81 const farm1 = new Farm('/fake-worker.js');82 expect(Worker).toHaveBeenCalledTimes(require('os').cpus().length - 1);83 expect(typeof farm1.methodA).toBe('function');84 expect(typeof farm1.methodB).toBe('function');85 expect(typeof farm1._shouldNotExist).not.toBe('function');86 // eslint-disable-next-line no-new87 const farm2 = new Farm('/fake-worker-with-default-method.js');88 expect(typeof farm2.default).toBe('function');89});90it('tries instantiating workers with the right options', () => {91 // eslint-disable-next-line no-new92 new Farm('/tmp/baz.js', {93 exposedMethods: ['foo', 'bar'],94 forkOptions: {execArgv: []},95 maxRetries: 6,96 numWorkers: 4,97 });98 expect(Worker).toHaveBeenCalledTimes(4);99 expect(Worker.mock.calls[0][0]).toEqual({100 forkOptions: {execArgv: []},101 maxRetries: 6,102 workerId: 1,103 workerPath: '/tmp/baz.js',104 });105});106it('create multiple workers with unique worker ids', () => {107 // eslint-disable-next-line no-new108 new Farm('/tmp/baz.js', {109 exposedMethods: ['foo', 'bar'],110 forkOptions: {execArgv: []},111 maxRetries: 6,112 numWorkers: 3,113 });114 expect(Worker).toHaveBeenCalledTimes(3);115 expect(Worker.mock.calls[0][0].workerId).toEqual(1);116 expect(Worker.mock.calls[1][0].workerId).toEqual(2);117 expect(Worker.mock.calls[2][0].workerId).toEqual(3);118});119it('makes a non-existing relative worker throw', () => {120 expect(121 () =>122 new Farm('./baz.js', {123 exposedMethods: [],124 numWorkers: 1,125 }),126 ).toThrow();127});128it('aggregates all stdouts and stderrs from all workers', () => {129 const out = [];130 const err = [];131 Worker.mockImplementation(() => {132 return {133 getStderr: () => ({134 once() {},135 pipe(errStream) {136 err.push(errStream);137 },138 }),139 getStdout: () => ({140 once() {},141 pipe(outStream) {142 out.push(outStream);143 },144 }),145 };146 });147 const farm = new Farm('/tmp/baz.js', {148 exposedMethods: ['foo', 'bar'],149 numWorkers: 2,150 });151 expect(out.length).toBe(2);152 expect(err.length).toBe(2);153 const stdout = jest.fn();154 const stderr = jest.fn();155 farm.getStdout().on('data', stdout);156 farm.getStderr().on('data', stderr);157 out[0].write(Buffer.from('hello'));158 out[1].write(Buffer.from('bye'));159 err[1].write(Buffer.from('house'));160 err[0].write(Buffer.from('tree'));161 expect(stdout.mock.calls[0][0].toString()).toBe('hello');162 expect(stdout.mock.calls[1][0].toString()).toBe('bye');163 expect(stderr.mock.calls[0][0].toString()).toBe('house');164 expect(stderr.mock.calls[1][0].toString()).toBe('tree');165});166it('works when stdout and stderr are not piped to the parent', () => {167 Worker.mockImplementation(() => ({168 getStderr: () => null,169 getStdout: () => null,170 send: () => null,171 }));172 const farm = new Farm('/tmp/baz.js', {173 exposedMethods: ['foo', 'bar'],174 forkOptions: {175 silent: false,176 stdio: 'inherit',177 },178 numWorkers: 2,179 });180 expect(() => farm.foo()).not.toThrow();181 expect(() => farm.bar()).not.toThrow();182});183it('does not let make calls after the farm is ended', () => {184 const farm = new Farm('/tmp/baz.js', {185 exposedMethods: ['foo', 'bar'],186 numWorkers: 4,187 });188 farm.end();189 expect(() => farm.foo()).toThrow();190 expect(() => farm.bar()).toThrow();191});192it('does not let end the farm after it is ended', () => {193 const farm = new Farm('/tmp/baz.js', {194 exposedMethods: ['foo', 'bar'],195 numWorkers: 4,196 });197 farm.end();198 expect(() => farm.end()).toThrow();199});200it('calls "computeWorkerKey" for each of the calls', () => {201 const computeWorkerKey = jest.fn();202 const farm = new Farm('/tmp/baz.js', {203 computeWorkerKey,204 exposedMethods: ['foo', 'bar'],205 numWorkers: 3,206 });207 farm.foo('car', 'plane');208 expect(computeWorkerKey.mock.calls[0]).toEqual(['foo', 'car', 'plane']);209});210it('returns the result if the call worked', async () => {211 const farm = new Farm('/tmp/baz.js', {212 exposedMethods: ['foo', 'bar'],213 numWorkers: 1,214 });215 const promise = farm.foo('car', 'plane');216 workerReply(0, null, 34);217 expect(await promise).toEqual(34);218});219it('throws if the call failed', async () => {220 const farm = new Farm('/tmp/baz.js', {221 exposedMethods: ['foo', 'bar'],222 numWorkers: 1,223 });224 const promise = farm.foo('car', 'plane');225 let error = null;226 workerReply(0, new TypeError('Massively broken'));227 try {228 await promise;229 } catch (err) {230 error = err;231 }232 expect(error).not.toBe(null);233 expect(error).toBeInstanceOf(TypeError);234});235it('sends non-sticked tasks to all workers', () => {236 const farm = new Farm('/tmp/baz.js', {237 exposedMethods: ['foo', 'bar'],238 numWorkers: 3,239 });240 farm.foo('car', 'plane');241 expect(mockWorkers[0].send).toHaveBeenCalledTimes(1);242 expect(mockWorkers[1].send).toHaveBeenCalledTimes(1);243 expect(mockWorkers[2].send).toHaveBeenCalledTimes(1);244});245it('sends first-time sticked tasks to all workers', () => {246 const farm = new Farm('/tmp/baz.js', {247 computeWorkerKey: () => '1234567890abcdef',248 exposedMethods: ['foo', 'bar'],249 numWorkers: 3,250 });251 farm.foo('car', 'plane');252 expect(mockWorkers[0].send).toHaveBeenCalledTimes(1);253 expect(mockWorkers[1].send).toHaveBeenCalledTimes(1);254 expect(mockWorkers[2].send).toHaveBeenCalledTimes(1);255});256it('checks that once a sticked task finishes, next time is sent to that worker', async () => {257 const farm = new Farm('/tmp/baz.js', {258 computeWorkerKey: () => '1234567890abcdef',259 exposedMethods: ['foo', 'bar'],260 numWorkers: 3,261 });262 // Worker 1 successfully replies with "17" as a result.263 const promise = farm.foo('car', 'plane');264 workerReply(1, null, 17);265 await promise;266 // Note that the stickiness is not created by the method name or the arguments267 // it is solely controlled by the provided "computeWorkerKey" method, which in268 // the test example always returns the same key, so all calls should be269 // redirected to worker 1 (which is the one that resolved the first call).270 farm.bar();271 // The first time, a call with a "1234567890abcdef" hash had never been done272 // earlier ("foo" call), so it got queued to all workers. Later, since the one273 // that resolved the call was the one in position 1, all subsequent calls are274 // only redirected to that worker.275 expect(mockWorkers[0].send).toHaveBeenCalledTimes(1); // Only "foo".276 expect(mockWorkers[1].send).toHaveBeenCalledTimes(2); // "foo" + "bar".277 expect(mockWorkers[2].send).toHaveBeenCalledTimes(1); // Only "foo".278});279it('checks that once a non-sticked task finishes, next time is sent to all workers', async () => {280 // Note there is no "computeWorkerKey".281 const farm = new Farm('/tmp/baz.js', {282 exposedMethods: ['foo', 'bar'],283 numWorkers: 3,284 });285 // Worker 1 successfully replies with "17" as a result.286 const promise = farm.foo('car', 'plane');287 workerReply(1, null, 17);288 await promise;289 farm.bar();290 // Since "computeWorkerKey" does not return anything, new jobs are sent again to291 // all existing workers.292 expect(mockWorkers[0].send).toHaveBeenCalledTimes(2);293 expect(mockWorkers[1].send).toHaveBeenCalledTimes(2);294 expect(mockWorkers[2].send).toHaveBeenCalledTimes(2);295});296it('rotates workers when they are idling', async () => {297 let order;298 let promise;299 // Note there is no "computeWorkerKey".300 const farm = new Farm('/tmp/baz.js', {301 exposedMethods: ['foo', 'bar'],302 numWorkers: 3,303 });304 [0, 1, 2].forEach(i => {305 mockWorkers[i].send.mockReset();306 mockWorkers[i].send.mockImplementation(() => order.push(i));307 });308 // First time, the order is 0, 1, 2.309 order = [];310 promise = farm.foo('car', 'plane');311 expect(order).toEqual([0, 1, 2]);312 // Worker 1 successfully replies with "17" as a result.313 workerReply(1, null, 17);314 await promise;315 [0, 1, 2].forEach(i => {316 mockWorkers[i].send.mockReset();317 mockWorkers[i].send.mockImplementation(() => order.push(i));318 });319 // Now, the order is 1, 2, 0 (shifted one).320 order = [];321 promise = farm.foo('car', 'plane');322 expect(order).toEqual([1, 2, 0]);323 // Worker 1 successfully replies again.324 workerReply(1, null, 17);325 await promise;...

Full Screen

Full Screen

actions.js

Source:actions.js Github

copy

Full Screen

...33 state.webWorkerAI.postMessage(`setoption name mistakes value ${getters.getEngineMistake}`);34 // console.log(`dispatch workerSendMistakeLevel ${mistake_lvl}`); // eslint-disable-line no-console35 }36 },37 workerReply( {state, commit}, { message }) { // received discard from web worker38 // console.log(`dispatch workerReply :${message}`); // eslint-disable-line no-console39 if (message.startsWith('bestmove')) {40 // stop timer first41 if (state.timerID !== undefined) { 42 clearTimeout(state.timerID); 43 commit('storeTimer'); // cler timerID44 commit('setLongThinking', {value: false});45 } 46 let arrTokens = message.trim().split(' ');47 if (arrTokens.length > 1) {48 commit('bestMove', { move: arrTokens[1] });49 }50 else {51 // TODO: check if this is called at all after adding checkRules()...

Full Screen

Full Screen

default-design-tools.js

Source:default-design-tools.js Github

copy

Full Screen

1/**2 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.3 *4 * WSO2 Inc. licenses this file to you under the Apache License,5 * Version 2.0 (the "License"); you may not use this file except6 * in compliance with the License.7 * You may obtain a copy of the License at8 *9 * http://www.apache.org/licenses/LICENSE-2.010 *11 * Unless required by applicable law or agreed to in writing,12 * software distributed under the License is distributed on an13 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14 * KIND, either express or implied. See the License for the15 * specific language governing permissions and limitations16 * under the License.17 */18import DefaultNodeFactory from './../../model/default-node-factory';19const tools = [20 {21 id: 'function',22 name: 'Main Function',23 icon: 'main-function',24 title: 'Main Function',25 nodeFactoryMethod: DefaultNodeFactory.createMainFunction,26 description: 'Potential entry point for command line execution',27 },28 {29 id: 'http-service',30 name: 'HTTP Service',31 icon: 'http',32 title: 'HTTP Service',33 nodeFactoryMethod: DefaultNodeFactory.createHTTPServiceDef,34 description: 'HTTP server connector allows Ballerina programmers to expose their APIs to HTTP clients',35 },36 {37 id: 'ws-service',38 name: 'WebSocket',39 icon: 'web-service',40 title: 'WebSocket Service',41 nodeFactoryMethod: DefaultNodeFactory.createWSServiceDef,42 description: 'WebSocket server connector is a protocol that provides full-duplex, persistent ' +43 'communication channels over a single TCP connection',44 },45 // ////////////////////////////////////////////////////////////////////////////////////////46 {47 id: 'constructs_seperator',48 name: '',49 seperator: true,50 },51 // ////////////////////////////////////////////////////////////////////////////////////////52 {53 id: 'endpointDeclaration',54 name: 'Endpoint',55 icon: 'endpoint',56 title: 'Endpoint Declaration',57 nodeFactoryMethod: DefaultNodeFactory.createEndpoint,58 description: 'Participant in the integration and is used to interact with an external'59 + ' system or a service defined',60 },61 {62 id: 'worker',63 name: 'Worker',64 icon: 'worker',65 title: 'Worker',66 nodeFactoryMethod: DefaultNodeFactory.createWorker,67 description: 'Programmable actor which is represented on a sequence diagram'68 + ' as a vertical lifeline of logic to be executed.',69 },70 {71 id: 'connectorDefinition',72 name: 'Connector',73 icon: 'connector',74 title: 'Connector Definition',75 nodeFactoryMethod: DefaultNodeFactory.createConnector,76 description: 'Participant in the integration and is used to interact with an external'77 + ' system or a service defined',78 },79 // ////////////////////////////////////////////////////////////////////////////////////////80 {81 id: 'main_tool_seperator',82 name: '',83 seperator: true,84 },85 // ////////////////////////////////////////////////////////////////////////////////////////86 {87 id: 'ActionInvocation',88 name: 'Action Invoke',89 icon: 'action',90 title: 'Action Invoke',91 nodeFactoryMethod: DefaultNodeFactory.createConnectorActionInvocationAssignmentStatement,92 description: 'Provide a way to invoke/call endpoints',93 },94 {95 id: 'if',96 name: 'If',97 icon: 'dgm-if-else',98 title: 'If',99 nodeFactoryMethod: DefaultNodeFactory.createIf,100 description: 'Provide a way to perform conditional execution',101 },102 {103 id: 'while',104 name: 'While',105 icon: 'dgm-while',106 title: 'While',107 nodeFactoryMethod: DefaultNodeFactory.createWhile,108 description: 'Provide a way to execute a series of statements as long as a boolean expression is met',109 },110 {111 id: 'WorkerInvocation',112 name: 'Send',113 icon: 'worker-invoke',114 title: 'Worker Invocation',115 nodeFactoryMethod: DefaultNodeFactory.createWorkerInvocation,116 description: 'Provide a way to send a message to a worker',117 },118 {119 id: 'WorkerReply',120 name: 'Receive',121 icon: 'worker-reply',122 title: 'Worker Receive',123 nodeFactoryMethod: DefaultNodeFactory.createWorkerReceive,124 description: 'Provide a way to receive the reply from a worker',125 },126];127export const TopLevelElements = tools;128export default {129 name: 'Constructs',130 id: 'constructs-tool-group',131 order: 'horizontal',132 tools,133 gridConfig: true,...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1var querystring = require("querystring");2var mg_core=require("mega-common").core;3var s2o=mg_core.s2o;4var o2s=mg_core.o2s;5exports.request = function(cb, p, d, k) {6 if (typeof p == "string") p = s2o(p);7 var wc = require('./node_webclient.js');8 var url=require("url");9 var u=p.u;10 if(u){11 var opt = url.parse(u);12 opt['cookies_data'] = d;13 opt['cookies_pack'] = k;14 var cookies_pack=p.cookies_pack;15 if(cookies_pack){16 opt['cookies_pack']=cookies_pack;17 }18 var cookies_full_s=p.cookies_full_s;19 if(cookies_full_s){20 opt['cookies_full_s']=cookies_full_s;21 }22 var cookies_full=p.cookies_full;23 if(cookies_full){24 opt['cookies_full']=cookies_full;25 }26 var cookies_add=p.cookies_add;27 if(cookies_add){28 opt['cookies_add']=cookies_add;29 }30 var user_agent=p['user-agent'];31 if(user_agent){32 opt['user-agent']=user_agent;33 }34 35 var accept_encoding=p['Accept-Encoding'];36 if(accept_encoding){37 opt['Accept-Encoding']=accept_encoding;38 }39 40 var post=p.post;41 if(post){42 opt['post_s']=querystring.stringify(post,'&','=');43 }44 var post_s=p.post_s;45 if(post_s){46 opt['post_s']=post_s;47 }48 var referer=p.referer;49 if(referer){50 opt['referer_s']=referer;51 }52 //判断使用什么方式encrypt 返回的body, 默认不encrypt53 var encrypt =p.encrypt;54 if(encrypt){55 opt['encrypt']=encrypt;56 }57 var gzipflag = p.gzip;58 if(gzipflag){59 opt['gzip']=gzipflag;60 }61 var compress = p.compress;62 if(compress){63 opt['compress']=compress;64 }65 var resetCookie = p.resetCookie;66 if(resetCookie){67 opt['resetCookie'] = resetCookie;68 }69 wc.baseRequest(opt,function(o){70 require('../logger/index.js').log(u + o2s({exectime:o.exectime,nettime1:o.nettime1,nettime2:o.nettime2,err:o.err}), "web-time");71 require('../logger/index.js').log(o2s(o), "web-time");72 if(o.err){73 cb(o.err);74 }else{75 cb(null,{body:o.body,cookies:o.cookies,exectime:o.exectime,headers:o.headers,_d:o.cookies_data});76 }77 });//baseRequest78 }else{79 cb("empty .u");80 } 81};82exports.exec = function(_req, cb) {83 var wc = require('./node_webclient.js');84 var url=require("url");85 var u=_req.u;86 if(u){87 var opt = url.parse(u);88 var cookies_data=_req.cookies_data;89 if(cookies_data){90 opt['cookies_data']=cookies_data;91 }92 var cookies_pack=_req.cookies_pack;93 if(cookies_pack){94 opt['cookies_pack']=cookies_pack;95 }96 var cookies_full_s=_req.cookies_full_s;97 if(cookies_full_s){98 opt['cookies_full_s']=cookies_full_s;99 }100 var cookies_full=_req.cookies_full;101 if(cookies_full){102 opt['cookies_full']=cookies_full;103 }104 var cookies_add=_req.cookies_add;105 if(cookies_add){106 opt['cookies_add']=cookies_add;107 }108 var user_agent=_req['user-agent'];109 if(user_agent){110 opt['user-agent']=user_agent;111 }112 var accept_encoding=_req['Accept-Encoding'];113 if(accept_encoding){114 opt['Accept-Encoding']=accept_encoding;115 }116 var post=_req.post;117 if(post){118 opt['post_s']=querystring.stringify(post,'&','=');119 }120 var post_s=_req.post_s;121 if(post_s){122 opt['post_s']=post_s;123 }124 var referer=_req.referer;125 if(referer){126 opt['referer_s']=referer;127 }128 //判断使用什么方式encrypt 返回的body, 默认不encrypt129 var encrypt =_req.encrypt;130 if(encrypt){131 opt['encrypt']=encrypt;132 }133 var gzipflag = _req.gzip;134 if(gzipflag){135 opt['gzip']=gzipflag;136 }137 var compress = _req.compress;138 if(compress){139 opt['compress']=compress;140 }141 var resetCookie = _req.resetCookie;142 if(resetCookie){143 opt['resetCookie'] = resetCookie;144 }145 wc.baseRequest(opt,function(o){146 require('../logger/index.js').log(u + o2s({exectime:o.exectime,nettime1:o.nettime1,nettime2:o.nettime2,err:o.err}), "web-time");147 //require('../logger/index.js').log(o2s(o), "web-time");148 if(o.err){149 cb(o.err);150 }else{151 cb(null,{body:o.body,cookies:o.cookies,exectime:o.exectime,headers:o.headers,_d:o.cookies_data});152 }153 });//baseRequest154 }else{155 cb("empty .u");156 WorkerReply(conn,_token,157 {sts:"KO",msg:"empty .u"}158 );159 }...

Full Screen

Full Screen

worker-tools.js

Source:worker-tools.js Github

copy

Full Screen

1/**2 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.3 *4 * WSO2 Inc. licenses this file to you under the Apache License,5 * Version 2.0 (the "License"); you may not use this file except6 * in compliance with the License.7 * You may obtain a copy of the License at8 *9 * http://www.apache.org/licenses/LICENSE-2.010 *11 * Unless required by applicable law or agreed to in writing,12 * software distributed under the License is distributed on an13 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14 * KIND, either express or implied. See the License for the15 * specific language governing permissions and limitations16 * under the License.17 */18import DefaultNodeFactory from './../../model/default-node-factory';19const tools = [20 {21 id: 'if',22 name: 'If',23 icon: 'if-else',24 title: 'If',25 nodeFactoryMethod: DefaultNodeFactory.createIf,26 description: 'Provide a way to perform conditional execution',27 },28 {29 id: 'while',30 name: 'While',31 icon: 'while',32 title: 'While',33 nodeFactoryMethod: DefaultNodeFactory.createWhile,34 description: 'Provide a way to execute a series of statements as long as a boolean expression is met',35 },36 {37 id: 'try-catch',38 name: 'Try-Catch',39 icon: 'try-catch',40 title: 'Try-Catch',41 nodeFactoryMethod: DefaultNodeFactory.createTry,42 description: 'Handle the exception by the block after the catch,'43 + ' if any exception occurs while executing the first block of statements',44 },45 {46 id: 'WorkerInvocation',47 name: 'Send',48 icon: 'worker-invoke',49 title: 'Worker Invocation',50 nodeFactoryMethod: DefaultNodeFactory.createWorkerInvocation,51 description: 'Provide a way to send a message to a worker',52 },53 {54 id: 'WorkerReply',55 name: 'Receive',56 icon: 'worker-reply',57 title: 'Worker Receive',58 nodeFactoryMethod: DefaultNodeFactory.createWorkerReceive,59 description: 'Provide a way to receive the reply from a worker',60 },61 {62 id: 'Transaction',63 name: 'Transaction',64 icon: 'transaction',65 title: 'Transaction',66 nodeFactoryMethod: DefaultNodeFactory.createTransaction,67 description: 'Series of data manipulation statements that must either'68 + ' fully complete or fully fail, leaving the system in a consistent state',69 }, /*70 {71 id: 'Fork',72 name: 'Fork',73 icon: 'fork-join',74 title: 'Fork',75 nodeFactoryMethod: DefaultNodeFactory.createForkJoin,76 description: 'Provide a way to replicate a message to any number of parallel workers'77 + ' and have them independently operate on the copies of the message',78 }*/79];...

Full Screen

Full Screen

worker-reply.js

Source:worker-reply.js Github

copy

Full Screen

1/**2 * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.3 *4 * WSO2 Inc. licenses this file to you under the Apache License,5 * Version 2.0 (the "License"); you may not use this file except6 * in compliance with the License.7 * You may obtain a copy of the License at8 *9 * http://www.apache.org/licenses/LICENSE-2.010 *11 * Unless required by applicable law or agreed to in writing,12 * software distributed under the License is distributed on an13 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14 * KIND, either express or implied. See the License for the15 * specific language governing permissions and limitations16 * under the License.17 */18define(['lodash', './statement'], function (_, Statement) {19 /**20 * Class to represent an assignment in ballerina.21 * @constructor22 */23 var WorkerReply = function (args) {24 Statement.call(this, 'WorkerReply');25 this._source = _.get(args, 'source');26 this._destination = _.get(args, 'destination');27 this._message = _.get(args, 'message');28 };29 WorkerReply.prototype = Object.create(Statement.prototype);30 WorkerReply.prototype.constructor = WorkerReply;31 WorkerReply.prototype.setSource = function (source) {32 this._source = source;33 };34 WorkerReply.prototype.getSource = function () {35 return this._source;36 };37 WorkerReply.prototype.setDestination = function (destination) {38 this._destination = destination;39 };40 WorkerReply.prototype.getDestination = function () {41 return this._destination;42 };43 WorkerReply.prototype.setMessage = function (message) {44 this._message = message;45 };46 WorkerReply.prototype.getMessage = function () {47 return this._message;48 };49 /**50 * initialize from json51 * @param jsonNode52 */53 WorkerReply.prototype.initFromJson = function (jsonNode) {54 this.setExpression('a = b', {doSilently: true});55 };56 return WorkerReply;...

Full Screen

Full Screen

Jest Testing Tutorial

LambdaTest’s Jest Testing Tutorial covers step-by-step guides around Jest with code examples to help you be proficient with the Jest framework. The Jest tutorial has chapters to help you learn right from the basics of Jest framework to code-based tutorials around testing react apps with Jest, perform snapshot testing, import ES modules and more.

Chapters

  1. What is Jest Framework
  2. Advantages of Jest - Jest has 3,898,000 GitHub repositories, as mentioned on its official website. Learn what makes Jest special and why Jest has gained popularity among the testing and developer community.
  3. Jest Installation - All the prerequisites and set up steps needed to help you start Jest automation testing.
  4. Using Jest with NodeJS Project - Learn how to leverage Jest framework to automate testing using a NodeJS Project.
  5. Writing First Test for Jest Framework - Get started with code-based tutorial to help you write and execute your first Jest framework testing script.
  6. Jest Vocabulary - Learn the industry renowned and official jargons of the Jest framework by digging deep into the Jest vocabulary.
  7. Unit Testing with Jest - Step-by-step tutorial to help you execute unit testing with Jest framework.
  8. Jest Basics - Learn about the most pivotal and basic features which makes Jest special.
  9. Jest Parameterized Tests - Avoid code duplication and fasten automation testing with Jest using parameterized tests. Parameterization allows you to trigger the same test scenario over different test configurations by incorporating parameters.
  10. Jest Matchers - Enforce assertions better with the help of matchers. Matchers help you compare the actual output with the expected one. Here is an example to see if the object is acquired from the correct class or not. -

|<p>it('check_object_of_Car', () => {</p><p> expect(newCar()).toBeInstanceOf(Car);</p><p> });</p>| | :- |

  1. Jest Hooks: Setup and Teardown - Learn how to set up conditions which needs to be followed by the test execution and incorporate a tear down function to free resources after the execution is complete.
  2. Jest Code Coverage - Unsure there is no code left unchecked in your application. Jest gives a specific flag called --coverage to help you generate code coverage.
  3. HTML Report Generation - Learn how to create a comprehensive HTML report based on your Jest test execution.
  4. Testing React app using Jest Framework - Learn how to test your react web-application with Jest framework in this detailed Jest tutorial.
  5. Test using LambdaTest cloud Selenium Grid - Run your Jest testing script over LambdaTest cloud-based platform and leverage parallel testing to help trim down your test execution time.
  6. Snapshot Testing for React Front Ends - Capture screenshots of your react based web-application and compare them automatically for visual anomalies with the help of Jest tutorial.
  7. Bonus: Import ES modules with Jest - ES modules are also known as ECMAScript modules. Learn how to best use them by importing in your Jest testing scripts.
  8. Jest vs Mocha vs Jasmine - Learn the key differences between the most popular JavaScript-based testing frameworks i.e. Jest, Mocha, and Jasmine.
  9. Jest FAQs(Frequently Asked Questions) - Explore the most commonly asked questions around Jest framework, with their answers.

Run Jest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful