forked from jestjs/jest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
testUtils.ts
78 lines (63 loc) · 2.15 KB
/
testUtils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import fs from 'fs';
import os from 'os';
import path from 'path';
import crypto from 'crypto';
import {sync as spawnSync, ExecaReturns} from 'execa';
import {skipSuiteOnWindows} from '@jest/test-utils';
const CIRCUS_PATH = require.resolve('../../build/');
const CIRCUS_RUN_PATH = require.resolve('../../build/run');
const CIRCUS_STATE_PATH = require.resolve('../../build/state');
const TEST_EVENT_HANDLER_PATH = require.resolve('./testEventHandler');
const BABEL_REGISTER_PATH = require.resolve('@babel/register');
skipSuiteOnWindows();
interface Result extends ExecaReturns {
status: number;
error: string;
}
export const runTest = (source: string) => {
const filename = crypto
.createHash('md5')
.update(source)
.digest('hex');
const tmpFilename = path.join(os.tmpdir(), filename);
const content = `
require('${BABEL_REGISTER_PATH}')({extensions: [".js", ".ts"]});
const circus = require('${CIRCUS_PATH}');
global.it = circus.it;
global.test = circus.test;
global.describe = circus.describe;
global.beforeEach = circus.beforeEach;
global.afterEach = circus.afterEach;
global.beforeAll = circus.beforeAll;
global.afterAll = circus.afterAll;
const testEventHandler = require('${TEST_EVENT_HANDLER_PATH}').default;
const addEventHandler = require('${CIRCUS_STATE_PATH}').addEventHandler;
addEventHandler(testEventHandler);
${source};
const run = require('${CIRCUS_RUN_PATH}').default;
run();
`;
fs.writeFileSync(tmpFilename, content);
// Normalize for compat with cross-spawn
let result: Result;
try {
result = spawnSync('node', [tmpFilename], {
cwd: process.cwd(),
}) as Result;
} catch (err) {
result = err;
}
fs.unlinkSync(tmpFilename);
return {
status: result.code,
stderr: String(result.stderr),
stdout: String(result.stdout),
};
};