How to use workerReplyStart method in Jest

Best JavaScript code snippet using jest

Farm.test.js

Source:Farm.test.js Github

copy

Full Screen

...7'use strict';8import Farm from '../Farm';9let mockWorkerCalls;10let callback;11function workerReplyStart(i) {12 mockWorkerCalls[i].onStart({getWorkerId: () => mockWorkerCalls[i].workerId});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 = elric.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 = elric.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 = elric109 .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, {175 computeWorkerKey: () => '1234567890abcdef',176 });177 // Worker 1 successfully replies with "17" as a result.178 const p0 = farm.doWork('car', 'plane');179 workerReply(0, null, 17);180 await p0;181 // Note that the stickiness is not created by the method name or the182 // arguments it is solely controlled by the provided "computeWorkerKey"183 // method, which in the test example always returns the same key, so all184 // calls should be redirected to worker 1 (which is the one that resolved185 // the first call).186 const p1 = farm.doWork('foo', 'bar');187 workerReply(1, null, 17);188 await p1;189 // The first time, a call with a "1234567890abcdef" hash had never been190 // done earlier ("foo" call), so it got queued to all workers. Later, since191 // the one that resolved the call was the one in position 1, all subsequent192 // calls are only redirected to that worker.193 expect(callback).toHaveBeenCalledTimes(2); // Only "foo".194 expect(callback).toHaveBeenNthCalledWith(195 1,196 0, // first worker197 [1, true, 'car', ['plane']],198 expect.any(Function),199 expect.any(Function),200 expect.any(Function),201 );202 expect(callback).toHaveBeenNthCalledWith(203 2,204 0, // first worker205 [1, true, 'foo', ['bar']],206 expect.any(Function),207 expect.any(Function),208 expect.any(Function),209 );210 });211 it('checks that even before a sticked task finishes, next time is sent to that worker', async () => {212 const farm = new Farm(4, callback, {213 computeWorkerKey: () => '1234567890abcdef',214 });215 // Note that the worker is sending a start response synchronously.216 const p0 = farm.doWork('car', 'plane');217 workerReplyStart(0);218 // Note that the worker is sending a start response synchronously.219 const p1 = farm.doWork('foo', 'bar');220 // The first call is sent the worker, the second is queued221 expect(callback).toHaveBeenCalledTimes(1);222 // Flush the queue223 workerReplyEnd(0, null, 17);224 await p0;225 workerReply(1, null, 17);226 await p1;227 // Both requests are send to the same worker. The first time, a call with228 // a "1234567890abcdef" hash had never been done earlier ("foo" call), so229 // it got queued to all workers. Later, since the one that resolved the230 // call was the one in position 1, all subsequent calls are only redirected231 // to that worker.232 expect(callback).toHaveBeenCalledTimes(2);233 expect(callback).toHaveBeenNthCalledWith(234 1,235 0, // first worker236 [1, true, 'car', ['plane']],237 expect.any(Function),238 expect.any(Function),239 expect.any(Function),240 );241 expect(callback).toHaveBeenNthCalledWith(242 2,243 0, // first worker244 [1, true, 'foo', ['bar']],245 expect.any(Function),246 expect.any(Function),247 expect.any(Function),248 );249 });250 it('checks that locking works, and jobs are never lost', async () => {251 const hash = elric252 .fn()253 // This will go to both queues, but picked by the first worker.254 .mockReturnValueOnce(0)255 // This will go to both queues too, but picked by the second worker.256 .mockReturnValueOnce(1)257 // This will go to worker 0, now only assigned to it.258 .mockReturnValueOnce(0)259 // This will go to worker 1, now only assigned to it.260 .mockReturnValueOnce(1)261 // This will go to both queues too, but will wait, since workers are busy.262 .mockReturnValueOnce(2)263 // This will only go to the first queue.264 .mockReturnValueOnce(0)265 // This will be gone if the queue implementation is wrong.266 .mockReturnValueOnce(0)267 // Push onto the second queue; potentially wiping the earlier job.268 .mockReturnValueOnce(1);269 const farm = new Farm(2, callback, {computeWorkerKey: hash});270 // First and second jobs get resolved, so that their hash is sticked to271 // the right worker: worker assignment is performed when workers reply, not272 // when the call is made.273 const p0 = farm.doWork('work-0');274 const p1 = farm.doWork('work-1');275 workerReply(0, null, 'response-0');276 await p0;277 workerReply(1, null, 'response-1');278 await p1;279 // Now we perform the rest of the calls (7 resolves before 5 and 6, since 4280 // is in both queues, and as soon as you resolve 4, 7 will be picked).281 const p2 = farm.doWork('work-2');282 const p3 = farm.doWork('work-3');283 const p4 = farm.doWork('work-4');284 const p5 = farm.doWork('work-5');285 const p6 = farm.doWork('work-6');286 const p7 = farm.doWork('work-7');287 workerReply(2, null, 'response-2');288 await p2;289 workerReply(3, null, 'response-3');290 await p3;291 workerReply(4, null, 'response-4');292 await p4;293 workerReply(5, null, 'response-7');294 await p7;295 workerReply(6, null, 'response-5');296 await p5;297 workerReply(7, null, 'response-6');298 await p6;299 await expect(p0).resolves.toBe('response-0');300 await expect(p1).resolves.toBe('response-1');301 await expect(p2).resolves.toBe('response-2');302 await expect(p3).resolves.toBe('response-3');303 await expect(p4).resolves.toBe('response-4');304 await expect(p5).resolves.toBe('response-5');305 await expect(p6).resolves.toBe('response-6');306 await expect(p7).resolves.toBe('response-7');307 });308 it('can receive custom messages from workers', async () => {309 expect.assertions(2);310 const farm = new Farm(2, callback);311 const p0 = farm.doWork('work-0');312 const p1 = farm.doWork('work-1');313 const unsubscribe = p0.UNSTABLE_onCustomMessage(message => {314 expect(message).toEqual({key: 0, message: 'foo'});315 });316 p1.UNSTABLE_onCustomMessage(message => {317 expect(message).toEqual({key: 1, message: 'bar'});318 });319 workerReplyStart(0);320 workerReplyStart(1);321 workerReplyCustomMessage(0, {key: 0, message: 'foo'});322 workerReplyCustomMessage(1, {key: 1, message: 'bar'});323 unsubscribe();324 // This message will not received because the listener already325 // unsubscribed.326 workerReplyCustomMessage(0, {key: 0, message: 'baz'});327 workerReply(0, null, 17);328 workerReply(1, null, 17);329 await p0;330 await p1;331 });...

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 workerReplyStart(i) {12 mockWorkers[i].send.mock.calls[0][1](mockWorkers[i]);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 });...

Full Screen

Full Screen

71index.test.js

Source:71index.test.js Github

copy

Full Screen

...7'use strict';8let Farm;9let Worker;10let mockWorkers;11function workerReplyStart(i) {12 mockWorkers[i].send.mock.calls[0][1](mockWorkers[i]);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 });...

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