How to use replySuccess 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.

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';
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.postMessage = 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].postMessage).toHaveBeenCalledTimes(
31    calls.length + 1,
32  );
33
34  calls.forEach(([methodName, ...args], numCall) => {
35    expect(
36      mockForkedProcesses[childNum].postMessage.mock.calls[numCall + 1][0],
37    ).toEqual([CHILD_MESSAGE_CALL, true, methodName, args]);
38  });
39}
40
41describe('Jest Worker Process Integration', () => {
42  beforeEach(() => {
43    mockForkedProcesses = [];
44
45    jest.mock('worker_threads', () => {
46      const fakeClass = jest.fn(() => {
47        const forkedProcess = mockBuildForkedProcess();
48
49        mockForkedProcesses.push(forkedProcess);
50
51        return forkedProcess;
52      });
53
54      return {
55        Worker: fakeClass,
56        __esModule: true,
57      };
58    });
59
60    Farm = require('../index').default;
61  });
62
63  afterEach(() => {
64    jest.resetModules();
65  });
66
67  it('calls a single method from the worker', async () => {
68    const farm = new Farm('/tmp/baz.js', {
69      enableWorkerThreads: true,
70      exposedMethods: ['foo', 'bar'],
71      numWorkers: 4,
72    });
73
74    const promise = farm.foo();
75
76    replySuccess(0, 42);
77
78    expect(await promise).toBe(42);
79  });
80
81  it('distributes sequential calls across child processes', async () => {
82    const farm = new Farm('/tmp/baz.js', {
83      enableWorkerThreads: true,
84      exposedMethods: ['foo', 'bar'],
85      numWorkers: 4,
86    });
87
88    // The first call will go to the first child process.
89    const promise0 = farm.foo('param-0');
90
91    assertCallsToChild(0, ['foo', 'param-0']);
92    replySuccess(0, 'worker-0');
93    expect(await promise0).toBe('worker-0');
94
95    // The second call will go to the second child process.
96    const promise1 = farm.foo(1);
97
98    assertCallsToChild(1, ['foo', 1]);
99    replySuccess(1, 'worker-1');
100    expect(await promise1).toBe('worker-1');
101  });
102
103  it('distributes concurrent calls across child processes', async () => {
104    const farm = new Farm('/tmp/baz.js', {
105      enableWorkerThreads: true,
106      exposedMethods: ['foo', 'bar'],
107      numWorkers: 4,
108    });
109
110    // Do 3 calls to the farm in parallel.
111    const promise0 = farm.foo('param-0');
112    const promise1 = farm.foo('param-1');
113    const promise2 = farm.foo('param-2');
114
115    // Check that the method calls are sent to each separate child process.
116    assertCallsToChild(0, ['foo', 'param-0']);
117    assertCallsToChild(1, ['foo', 'param-1']);
118    assertCallsToChild(2, ['foo', 'param-2']);
119
120    // Send different responses from each child.
121    replySuccess(0, 'worker-0');
122    replySuccess(1, 'worker-1');
123    replySuccess(2, 'worker-2');
124
125    // Check
126    expect(await promise0).toBe('worker-0');
127    expect(await promise1).toBe('worker-1');
128    expect(await promise2).toBe('worker-2');
129  });
130
131  it('sticks parallel calls to children', async () => {
132    const farm = new Farm('/tmp/baz.js', {
133      computeWorkerKey: () => '1234567890abcdef',
134      enableWorkerThreads: true,
135      exposedMethods: ['foo', 'bar'],
136      numWorkers: 4,
137    });
138
139    // Do 3 calls to the farm in parallel.
140    const promise0 = farm.foo('param-0');
141    const promise1 = farm.foo('param-1');
142    const promise2 = farm.foo('param-2');
143
144    // Send different responses for each call (from the same child).
145    replySuccess(0, 'worker-0');
146    replySuccess(0, 'worker-1');
147    replySuccess(0, 'worker-2');
148
149    // Check that all the calls have been received by the same child).
150    assertCallsToChild(
151      0,
152      ['foo', 'param-0'],
153      ['foo', 'param-1'],
154      ['foo', 'param-2'],
155    );
156
157    // Check that responses are correct.
158    expect(await promise0).toBe('worker-0');
159    expect(await promise1).toBe('worker-1');
160    expect(await promise2).toBe('worker-2');
161  });
162});
163
Full Screen

process-integration.test.js

Source: process-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';
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
41jest.mock('worker_threads', () => {
42  throw Error('Unsupported');
43});
44
45describe('Jest Worker Integration', () => {
46  beforeEach(() => {
47    mockForkedProcesses = [];
48
49    jest.mock('child_process', () => ({
50      fork() {
51        const forkedProcess = mockBuildForkedProcess();
52
53        mockForkedProcesses.push(forkedProcess);
54
55        return forkedProcess;
56      },
57    }));
58
59    Farm = require('../index').default;
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      exposedMethods: ['foo', 'bar'],
69      numWorkers: 4,
70    });
71
72    const promise = farm.foo();
73
74    replySuccess(0, 42);
75
76    expect(await promise).toBe(42);
77  });
78
79  it('distributes sequential calls across child processes', async () => {
80    const farm = new Farm('/tmp/baz.js', {
81      exposedMethods: ['foo', 'bar'],
82      numWorkers: 4,
83    });
84
85    // The first call will go to the first child process.
86    const promise0 = farm.foo('param-0');
87
88    assertCallsToChild(0, ['foo', 'param-0']);
89    replySuccess(0, 'worker-0');
90    expect(await promise0).toBe('worker-0');
91
92    // The second call will go to the second child process.
93    const promise1 = farm.foo(1);
94
95    assertCallsToChild(1, ['foo', 1]);
96    replySuccess(1, 'worker-1');
97    expect(await promise1).toBe('worker-1');
98  });
99
100  it('distributes concurrent calls across child processes', async () => {
101    const farm = new Farm('/tmp/baz.js', {
102      exposedMethods: ['foo', 'bar'],
103      numWorkers: 4,
104    });
105
106    // Do 3 calls to the farm in parallel.
107    const promise0 = farm.foo('param-0');
108    const promise1 = farm.foo('param-1');
109    const promise2 = farm.foo('param-2');
110
111    // Check that the method calls are sent to each separate child process.
112    assertCallsToChild(0, ['foo', 'param-0']);
113    assertCallsToChild(1, ['foo', 'param-1']);
114    assertCallsToChild(2, ['foo', 'param-2']);
115
116    // Send different responses from each child.
117    replySuccess(0, 'worker-0');
118    replySuccess(1, 'worker-1');
119    replySuccess(2, 'worker-2');
120
121    // Check
122    expect(await promise0).toBe('worker-0');
123    expect(await promise1).toBe('worker-1');
124    expect(await promise2).toBe('worker-2');
125  });
126
127  it('sticks parallel calls to children', async () => {
128    const farm = new Farm('/tmp/baz.js', {
129      computeWorkerKey: () => '1234567890abcdef',
130      exposedMethods: ['foo', 'bar'],
131      numWorkers: 4,
132    });
133
134    // Do 3 calls to the farm in parallel.
135    const promise0 = farm.foo('param-0');
136    const promise1 = farm.foo('param-1');
137    const promise2 = farm.foo('param-2');
138
139    // Send different responses for each call (from the same child).
140    replySuccess(0, 'worker-0');
141    replySuccess(0, 'worker-1');
142    replySuccess(0, 'worker-2');
143
144    // Check that all the calls have been received by the same child).
145    assertCallsToChild(
146      0,
147      ['foo', 'param-0'],
148      ['foo', 'param-1'],
149      ['foo', 'param-2'],
150    );
151
152    // Check that responses are correct.
153    expect(await promise0).toBe('worker-0');
154    expect(await promise1).toBe('worker-1');
155    expect(await promise2).toBe('worker-2');
156  });
157});
158
Full Screen

comments.js

Source: comments.js Github

copy
1'use strict';
2import React, { Component } from 'react';
3import styles from '../css/comments.css';
4import CommentBox from './CommentBox';
5
6
7class View extends Component {
8
9
10  constructor(props){
11    super(props)
12    this.state = {index:-1}
13    this.reply = this.reply.bind(this);
14    this.replySuccess = this.replySuccess.bind(this);
15  }
16
17  componentWillReceiveProps(nextProps){
18    this.state = {index:-1}
19  }
20
21  reply(index){
22    this.setState((prevState, props) => {
23        var state = prevState;
24        state.index =  index;
25        state.msg = undefined;
26        return state;
27    })
28  }
29
30  replySuccess(){
31    this.setState((prevState, props) => {
32        var state = prevState;
33        state.index =  state.index + 1;
34        state.msg = window.getString('postSuccess')
35        return state;
36    })
37
38  }
39
40  render(){
41
42    var that = this;
43    var commentDivs = this.props.comments.map(function(comment,i) {
44      var tag = ""
45      var msg = ""
46
47      if(i === that.state.index && that.state.msg){
48        msg =  <div className="msg">{that.state.msg}</div>
49        tag = <button type="button"  onClick={() => that.reply(i)}>{window.getString("commentReply")}</button>
50      }else if(i != that.state.index)
51        tag = <button type="button"  onClick={() => that.reply(i)}>{window.getString("commentReply")}</button>
52      else{
53        tag = <CommentBox replySuccess={that.replySuccess} publishComment={that.props.publishComment} title={window.getString("commentReply")} replyTo={comment.userEmail} mention={comment.userName}/>
54      }
55
56      var userName = comment.userName
57
58      if(!userName){
59        userName = window.getString("anonymous")
60      }
61      userName = userName+":"
62
63      return(<li key={i} className="comment">
64        <div className="userName">{userName}</div>
65        <div className="text">{comment.text}</div>
66        {msg}
67        {tag}
68      </li>)
69    })
70
71    var moreTag = ""
72    if(this.props.comments.length >0  && this.props.comments.length%5 == 0 ){
73          moreTag = <li className="moreComments"><button onClick={this.props.showMoreComments} type="button">{window.getString("more")}</button></li>
74    }
75
76    return(
77      <ul className="comments">
78        <div className="title">{window.getString("comments")}</div>
79        {commentDivs}
80        {moreTag}
81      </ul>
82    )
83  }
84}
85
86export default View;
87
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)