How to use createTestRunMock method in Testcafe

Best JavaScript code snippet using testcafe

Run Testcafe automation tests on LambdaTest cloud grid

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

execute-async-expression-test.js

Source: execute-async-expression-test.js Github

copy
1const { noop } = require('lodash');
2const nanoid   = require('nanoid');
3const expect   = require('chai').expect;
4
5const TestRun        = require('../../lib/test-run/index');
6const TestController = require('../../lib/api/test-controller');
7const COMMAND_TYPE   = require('../../lib/test-run/commands/type');
8const markerSymbol   = require('../../lib/test-run/marker-symbol');
9const debugLogger    = require('../../lib/notifications/debug-logger');
10
11const assertTestRunError = require('./helpers/assert-test-run-error');
12
13let callsite = 0;
14
15function createTestRunMock () {
16    function TestRunMock () {
17        this.session         = { id: nanoid(7) };
18        this.test            = { name: 'Test', testFile: { filename: __filename } };
19        this.debugLog        = { command: noop };
20        this.controller      = new TestController(this);
21        this.driverTaskQueue = [];
22        this.emit            = noop;
23        this.debugLogger     = debugLogger;
24
25        this[markerSymbol] = true;
26
27        this.browserConnection = {
28            isHeadlessBrowser: () => false,
29            userAgent:         'Chrome'
30        };
31    }
32
33    TestRunMock.prototype = TestRun.prototype;
34
35    return new TestRunMock();
36}
37
38async function executeAsyncExpression (expression, testRun = createTestRunMock()) {
39    callsite++;
40
41    return await testRun.executeCommand({
42        type: COMMAND_TYPE.executeAsyncExpression,
43        expression
44    }, callsite.toString());
45}
46
47async function executeExpression (expression, customVarName, testRun = createTestRunMock()) {
48    return testRun.executeCommand({
49        type:               COMMAND_TYPE.executeExpression,
50        resultVariableName: customVarName,
51        expression
52    });
53}
54
55async function assertError (expression, expectedMessage, expectedLine, expectedColumn) {
56    let catched = false;
57
58    try {
59        await executeAsyncExpression(expression);
60    }
61    catch (err) {
62        catched = true;
63
64        expect(err.errMsg).eql(expectedMessage);
65        expect(err.line).eql(expectedLine);
66        expect(err.column).eql(expectedColumn);
67        expect(err.callsite).eql(callsite.toString());
68        expect(err.expression).eql(expression);
69    }
70
71    expect(catched).eql(true);
72}
73
74async function assertTestCafeError (expression, expectedFileName) {
75    let catched = false;
76
77    try {
78        await executeAsyncExpression(expression);
79    }
80    catch (err) {
81        catched = true;
82
83        assertTestRunError(err, expectedFileName, false);
84    }
85
86    expect(catched).eql(true);
87}
88
89describe('Code steps', () => {
90    beforeEach(() => {
91        callsite = 0;
92    });
93
94    it('basic', async () => {
95        const res = await executeAsyncExpression('return 1+1;');
96
97        expect(res).eql(2);
98    });
99
100    it('error', async () => {
101        await assertError('u=void 0;u.t=5;', 'Cannot set property \'t\' of undefined', 1, 13, '1');
102
103        await assertError(
104            'let q = void 0;\n' +
105            '        q.t = 5;'
106            , 'Cannot set property \'t\' of undefined', 2, 13, '2');
107
108        await assertError(
109            'let q = 3;\n' +
110            'q = 4;\n' +
111            'throw new Error(\'custom error\')'
112            , 'custom error', 3, 7, '3');
113    });
114
115    describe('TestCafe errors', () => {
116        it('Test run error', async () => {
117            await assertTestCafeError("await t.wait('10');", '../data/execute-async-expression/test-run-error');
118        });
119
120        it('Runtime run error', async () => {
121            await assertTestCafeError('const s = Selector();', '../data/execute-async-expression/runtime-error');
122        });
123    });
124
125    it('sync expression does not spoil global context', async () => {
126        const testRun = createTestRunMock();
127
128        await executeExpression('1+1', 'myCustomVar1', testRun);
129        await executeExpression('1+myCustomVar1', 'myCustomVar2', testRun);
130
131        expect(typeof myCustomVar1).eql('undefined');
132        expect(typeof myCustomVar2).eql('undefined');
133
134        expect(await executeExpression('myCustomVar1', void 0, testRun)).eql(2);
135        expect(await executeExpression('myCustomVar2', void 0, testRun)).eql(3);
136    });
137
138    it('shared context with global variables', async () => {
139        const testRun = createTestRunMock();
140
141        await executeAsyncExpression('result = 10;', testRun);
142
143        const res = await executeAsyncExpression('return result + 3', testRun);
144
145        expect(res).eql(13);
146        expect(typeof result).eql('undefined');
147    });
148
149    it('shared context with local variables', async () => {
150        const testRun = createTestRunMock();
151
152        await executeAsyncExpression('const result = 10;', testRun);
153
154        try {
155            await executeAsyncExpression('return result + 3', testRun);
156        }
157        catch (err) {
158            expect(err.code).eql('E66');
159            expect(err.errMsg).eql('result is not defined');
160        }
161    });
162
163    it('different context', async () => {
164        await executeAsyncExpression('result = 10;');
165
166        try {
167            await executeAsyncExpression('result + 3');
168        }
169        catch (err) {
170            expect(err.code).eql('E66');
171            expect(err.errMsg).eql('result is not defined');
172        }
173    });
174
175    it('promises', () => {
176        return executeAsyncExpression(`
177            return new Promise((resolve, reject) => {
178                setTimeout(() => {
179                    resolve('hooray!');
180                }, 20);
181            });
182        `)
183            .then(result => {
184                expect(result).eql('hooray!');
185            });
186    });
187
188    it('async/await', () => {
189        return executeAsyncExpression(`
190            const promise = new Promise((resolve, reject) => {
191                setTimeout(() => {
192                    resolve('hooray!');
193                }, 20);
194            });
195            
196            const result = await promise;
197            
198            return result;
199        `)
200            .then(result => {
201                expect(result).eql('hooray!');
202            });
203    });
204
205    it('require - absolute', async () => {
206        await executeAsyncExpression(`
207            return require('testcafe-hammerhead');
208        `)
209            .then(result => {
210                expect(result).eql(require('testcafe-hammerhead'));
211            });
212    });
213
214    it('require - relative', async () => {
215        await executeAsyncExpression(`
216            return require('./helpers/console-wrapper');
217        `)
218            .then(result => {
219                expect(result).eql(require('./helpers/console-wrapper'));
220            });
221    });
222
223    it('globals', async () => {
224        const result = await executeAsyncExpression(`
225            Buffer.from('test');
226
227            const timeout   = setTimeout(function () {});
228            const immediate = setImmediate(function () {});
229            const interval  = setInterval(function () {});
230
231            clearTimeout(timeout);
232            clearImmediate(immediate);
233            clearInterval(interval);
234            
235            return { __dirname, __filename };
236        `);
237
238        expect(result.__dirname).eql(__dirname);
239        expect(result.__filename).eql(__filename);
240    });
241
242    it('Selector/ClientFunction/Role/RequestMock/RequestHook/RequestLogger', async () => {
243        await executeAsyncExpression(`
244            const selector       = Selector('button');
245            const clientFunction = ClientFunction(() => {});
246            const role           = Role('http://example.com', () => {});
247            const mock           = RequestMock();
248            const logger         = RequestLogger();
249            const hook           = new RequestHook();
250        `);
251    });
252
253    describe('test controller', () => {
254        it('basic', async () => {
255            await executeAsyncExpression(`
256                await t.wait(10);
257            `);
258        });
259
260        it('shared context', async () => {
261            const testRun = createTestRunMock();
262
263            await executeAsyncExpression(`
264                t.testRun.sharedVar = 1;
265            `, testRun);
266
267            await executeAsyncExpression(`
268                if (!t.testRun.sharedVar)
269                    t.testRun.sharedVar = 2;
270            `, testRun);
271
272            expect(testRun.sharedVar).eql(1);
273        });
274
275        it('different context', async () => {
276            const testRun1 = createTestRunMock();
277            const testRun2 = createTestRunMock();
278
279            await executeAsyncExpression(`
280                t.testRun.sharedVar = 1;
281            `, testRun1);
282
283            await executeAsyncExpression(`
284                if (!t.testRun.sharedVar)
285                    t.testRun.sharedVar = 2;
286            `, testRun2);
287
288            expect(testRun1.sharedVar).eql(1);
289            expect(testRun2.sharedVar).eql(2);
290        });
291
292        it('debug', async () => {
293            const testRun = createTestRunMock();
294            let debugMsg  = '';
295            let err       = null;
296
297            testRun._enqueueCommand = () => Promise.resolve();
298
299            const initialWrite = process.stdout.write;
300
301            process.stdout.write = chunk => {
302                debugMsg += chunk.toString();
303            };
304
305            try {
306                await executeAsyncExpression('await t.debug();', testRun);
307            }
308            catch (e) {
309                err = e;
310            }
311
312            process.stdout.write = initialWrite;
313
314            expect(err).eql(null);
315            expect(debugMsg).contains('Chrome');
316            expect(debugMsg).contains('DEBUGGER PAUSE');
317        });
318    });
319});
320
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 Testcafe 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)