How to use assertCallsToChild method in Jest

Best JavaScript code snippet using jest

Run Jest automation tests on LambdaTest cloud grid

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

index-integration.test.js

Source: index-integration.test.js Github

copy
1/**
2 * Copyright (c) 2017-present, Facebook, Inc. All rights reserved.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8'use strict';
9
10import EventEmitter from 'events';
11
12import {CHILD_MESSAGE_CALL, PARENT_MESSAGE_OK} from '../types';
13
14let Farm;
15let mockForkedProcesses;
16
17function mockBuildForkedProcess() {
18  const mockChild = new EventEmitter();
19
20  mockChild.send = jest.fn();
21
22  return mockChild;
23}
24
25function replySuccess(i, result) {
26  mockForkedProcesses[i].emit('message', [PARENT_MESSAGE_OK, result]);
27}
28
29function assertCallsToChild(childNum, ...calls) {
30  expect(mockForkedProcesses[childNum].send).toHaveBeenCalledTimes(
31    calls.length + 1,
32  );
33
34  calls.forEach(([methodName, ...args], numCall) => {
35    expect(
36      mockForkedProcesses[childNum].send.mock.calls[numCall + 1][0],
37    ).toEqual([CHILD_MESSAGE_CALL, true, methodName, args]);
38  });
39}
40
41beforeEach(() => {
42  mockForkedProcesses = [];
43
44  jest.mock('child_process', () => ({
45    fork() {
46      const forkedProcess = mockBuildForkedProcess();
47
48      mockForkedProcesses.push(forkedProcess);
49
50      return forkedProcess;
51    },
52  }));
53
54  Farm = require('../index').default;
55});
56
57afterEach(() => {
58  jest.resetModules();
59});
60
61it('calls a single method from the worker', async () => {
62  const farm = new Farm('/tmp/baz.js', {
63    exposedMethods: ['foo', 'bar'],
64    numWorkers: 4,
65  });
66
67  const promise = farm.foo();
68
69  replySuccess(0, 42);
70
71  expect(await promise).toBe(42);
72});
73
74it('distributes sequential calls across child processes', async () => {
75  const farm = new Farm('/tmp/baz.js', {
76    exposedMethods: ['foo', 'bar'],
77    numWorkers: 4,
78  });
79
80  // The first call will go to the first child process.
81  const promise0 = farm.foo('param-0');
82
83  assertCallsToChild(0, ['foo', 'param-0']);
84  replySuccess(0, 'worker-0');
85  expect(await promise0).toBe('worker-0');
86
87  // The second call will go to the second child process.
88  const promise1 = farm.foo(1);
89
90  assertCallsToChild(1, ['foo', 1]);
91  replySuccess(1, 'worker-1');
92  expect(await promise1).toBe('worker-1');
93});
94
95it('distributes concurrent calls across child processes', async () => {
96  const farm = new Farm('/tmp/baz.js', {
97    exposedMethods: ['foo', 'bar'],
98    numWorkers: 4,
99  });
100
101  // Do 3 calls to the farm in parallel.
102  const promise0 = farm.foo('param-0');
103  const promise1 = farm.foo('param-1');
104  const promise2 = farm.foo('param-2');
105
106  // Check that the method calls are sent to each separate child process.
107  assertCallsToChild(0, ['foo', 'param-0']);
108  assertCallsToChild(1, ['foo', 'param-1']);
109  assertCallsToChild(2, ['foo', 'param-2']);
110
111  // Send different responses from each child.
112  replySuccess(0, 'worker-0');
113  replySuccess(1, 'worker-1');
114  replySuccess(2, 'worker-2');
115
116  // Check
117  expect(await promise0).toBe('worker-0');
118  expect(await promise1).toBe('worker-1');
119  expect(await promise2).toBe('worker-2');
120});
121
122it('sticks parallel calls to children', async () => {
123  const farm = new Farm('/tmp/baz.js', {
124    computeWorkerKey: () => '1234567890abcdef',
125    exposedMethods: ['foo', 'bar'],
126    numWorkers: 4,
127  });
128
129  // Do 3 calls to the farm in parallel.
130  const promise0 = farm.foo('param-0');
131  const promise1 = farm.foo('param-1');
132  const promise2 = farm.foo('param-2');
133
134  // Send different responses for each call (from the same child).
135  replySuccess(0, 'worker-0');
136  replySuccess(0, 'worker-1');
137  replySuccess(0, 'worker-2');
138
139  // Check that all the calls have been received by the same child).
140  assertCallsToChild(
141    0,
142    ['foo', 'param-0'],
143    ['foo', 'param-1'],
144    ['foo', 'param-2'],
145  );
146
147  // Check that responses are correct.
148  expect(await promise0).toBe('worker-0');
149  expect(await promise1).toBe('worker-1');
150  expect(await promise2).toBe('worker-2');
151});
152
Full Screen

thread-integration.test.js

Source: thread-integration.test.js Github

copy
1/**
2 * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8'use strict';
9
10import EventEmitter from 'events';
11import {CHILD_MESSAGE_CALL, PARENT_MESSAGE_OK} from '../types';
12
13let Farm;
14let mockForkedProcesses;
15
16function mockBuildForkedProcess() {
17  const mockChild = new EventEmitter();
18
19  mockChild.postMessage = jest.fn();
20
21  return mockChild;
22}
23
24function replySuccess(i, result) {
25  mockForkedProcesses[i].emit('message', [PARENT_MESSAGE_OK, result]);
26}
27
28function assertCallsToChild(childNum, ...calls) {
29  expect(mockForkedProcesses[childNum].postMessage).toHaveBeenCalledTimes(
30    calls.length + 1,
31  );
32
33  calls.forEach(([methodName, ...args], numCall) => {
34    expect(
35      mockForkedProcesses[childNum].postMessage.mock.calls[numCall + 1][0],
36    ).toEqual([CHILD_MESSAGE_CALL, true, methodName, args]);
37  });
38}
39
40describe('Jest Worker Process Integration', () => {
41  beforeEach(() => {
42    mockForkedProcesses = [];
43
44    jest.mock('worker_threads', () => {
45      const fakeClass = jest.fn(() => {
46        const forkedProcess = mockBuildForkedProcess();
47
48        mockForkedProcesses.push(forkedProcess);
49
50        return forkedProcess;
51      });
52
53      return {
54        Worker: fakeClass,
55        __esModule: true,
56      };
57    });
58
59    Farm = require('../index').Worker;
60  });
61
62  afterEach(() => {
63    jest.resetModules();
64  });
65
66  it('calls a single method from the worker', async () => {
67    const farm = new Farm('/tmp/baz.js', {
68      enableWorkerThreads: true,
69      exposedMethods: ['foo', 'bar'],
70      numWorkers: 4,
71    });
72
73    const promise = farm.foo();
74
75    replySuccess(0, 42);
76
77    expect(await promise).toBe(42);
78  });
79
80  it('distributes sequential calls across child processes', async () => {
81    const farm = new Farm('/tmp/baz.js', {
82      enableWorkerThreads: true,
83      exposedMethods: ['foo', 'bar'],
84      numWorkers: 4,
85    });
86
87    // The first call will go to the first child process.
88    const promise0 = farm.foo('param-0');
89    assertCallsToChild(0, ['foo', 'param-0']);
90    replySuccess(0, 'worker-0');
91    expect(await promise0).toBe('worker-0');
92
93    // The second call will go to the second child process.
94    const promise1 = farm.foo(1);
95    assertCallsToChild(1, ['foo', 1]);
96    replySuccess(1, 'worker-1');
97    expect(await promise1).toBe('worker-1');
98  });
99
100  it('schedules the task on the first available child processes if the scheduling policy is in-order', async () => {
101    const farm = new Farm('/tmp/baz.js', {
102      enableWorkerThreads: true,
103      exposedMethods: ['foo', 'bar'],
104      numWorkers: 4,
105      workerSchedulingPolicy: 'in-order',
106    });
107
108    // The first call will go to the first child process.
109    const promise0 = farm.foo('param-0');
110    assertCallsToChild(0, ['foo', 'param-0']);
111
112    // The second call will go to the second child process.
113    const promise1 = farm.foo(1);
114
115    // The first task on worker 0 completes
116    replySuccess(0, 'worker-0');
117    expect(await promise0).toBe('worker-0');
118
119    // The second task on worker 1 completes
120    assertCallsToChild(1, ['foo', 1]);
121    replySuccess(1, 'worker-1');
122    expect(await promise1).toBe('worker-1');
123
124    // The third call will go to the first child process
125    const promise2 = farm.foo('param-2');
126    assertCallsToChild(0, ['foo', 'param-0'], ['foo', 'param-2']);
127    replySuccess(0, 'worker-0');
128    expect(await promise2).toBe('worker-0');
129  });
130
131  it('schedules the task on the first available child processes', async () => {
132    const farm = new Farm('/tmp/baz.js', {
133      enableWorkerThreads: true,
134      exposedMethods: ['foo', 'bar'],
135      numWorkers: 4,
136    });
137
138    // The first call will go to the first child process.
139    const promise0 = farm.foo('param-0');
140    assertCallsToChild(0, ['foo', 'param-0']);
141    replySuccess(0, 'worker-0');
142    expect(await promise0).toBe('worker-0');
143
144    // The second call will go to the second child process.
145    const promise1 = farm.foo(1);
146    assertCallsToChild(1, ['foo', 1]);
147    replySuccess(1, 'worker-1');
148    expect(await promise1).toBe('worker-1');
149  });
150
151  it('distributes concurrent calls across child processes', async () => {
152    const farm = new Farm('/tmp/baz.js', {
153      enableWorkerThreads: true,
154      exposedMethods: ['foo', 'bar'],
155      numWorkers: 4,
156    });
157
158    // Do 3 calls to the farm in parallel.
159    const promise0 = farm.foo('param-0');
160    const promise1 = farm.foo('param-1');
161    const promise2 = farm.foo('param-2');
162
163    // Check that the method calls are sent to each separate child process.
164    assertCallsToChild(0, ['foo', 'param-0']);
165    assertCallsToChild(1, ['foo', 'param-1']);
166    assertCallsToChild(2, ['foo', 'param-2']);
167
168    // Send different responses from each child.
169    replySuccess(0, 'worker-0');
170    replySuccess(1, 'worker-1');
171    replySuccess(2, 'worker-2');
172
173    // Check
174    expect(await promise0).toBe('worker-0');
175    expect(await promise1).toBe('worker-1');
176    expect(await promise2).toBe('worker-2');
177  });
178
179  it('sticks parallel calls to children', async () => {
180    const farm = new Farm('/tmp/baz.js', {
181      computeWorkerKey: () => '1234567890abcdef',
182      enableWorkerThreads: true,
183      exposedMethods: ['foo', 'bar'],
184      numWorkers: 4,
185    });
186
187    // Do 3 calls to the farm in parallel.
188    const promise0 = farm.foo('param-0');
189    const promise1 = farm.foo('param-1');
190    const promise2 = farm.foo('param-2');
191
192    // Send different responses for each call (from the same child).
193    replySuccess(0, 'worker-0');
194    replySuccess(0, 'worker-1');
195    replySuccess(0, 'worker-2');
196
197    // Check that all the calls have been received by the same child).
198    assertCallsToChild(
199      0,
200      ['foo', 'param-0'],
201      ['foo', 'param-1'],
202      ['foo', 'param-2'],
203    );
204
205    // Check that responses are correct.
206    expect(await promise0).toBe('worker-0');
207    expect(await promise1).toBe('worker-1');
208    expect(await promise2).toBe('worker-2');
209  });
210});
211
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Jest on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)