Skip to content

Commit 1a86286

Browse files
authored
Add Jest Setup support for CRA (codesandbox#518)
1 parent 2f6e9a4 commit 1a86286

File tree

2 files changed

+35
-6
lines changed

2 files changed

+35
-6
lines changed

packages/app/src/app/components/Preview/DevTools/Tests/index.js

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -72,13 +72,15 @@ type State = {
7272
watching: boolean,
7373
};
7474

75+
const INITIAL_STATE = {
76+
files: {},
77+
selectedFilePath: null,
78+
running: true,
79+
watching: true,
80+
};
81+
7582
class Tests extends React.Component<Props, State> {
76-
state = {
77-
files: {},
78-
selectedFilePath: null,
79-
running: true,
80-
watching: true,
81-
};
83+
state = INITIAL_STATE;
8284

8385
listener: Function;
8486
currentDescribeBlocks: Array<string> = [];
@@ -113,6 +115,12 @@ class Tests extends React.Component<Props, State> {
113115
handleMessage = (data: Object) => {
114116
if (data.type === 'test') {
115117
switch (data.event) {
118+
case 'initialize_tests': {
119+
this.currentDescribeBlocks = [];
120+
this.props.updateStatus('clear');
121+
this.setState(INITIAL_STATE);
122+
break;
123+
}
116124
case 'total_test_start': {
117125
this.currentDescribeBlocks = [];
118126
this.props.updateStatus('clear');

packages/app/src/sandbox/eval/tests/jest-lite.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// @flow
22
import { dispatch, actions, listen } from 'codesandbox-api';
3+
import { react, reactTs } from 'common/templates';
34
import expect from 'jest-matchers';
45
import jestMock from 'jest-mock';
56
import jestTestHooks from 'jest-circus';
@@ -73,6 +74,8 @@ export default class TestRunner {
7374

7475
addEventHandler(this.handleMessage);
7576
listen(this.handleCodeSandboxMessage);
77+
78+
this.sendMessage('initialize_tests');
7679
}
7780

7881
testGlobals(module: Module) {
@@ -190,6 +193,24 @@ export default class TestRunner {
190193
}
191194

192195
this.sendMessage('total_test_start');
196+
197+
let testModule = null;
198+
199+
try {
200+
if (this.manager.preset.name === react.name) {
201+
testModule = this.manager.resolveModule('./src/setupTests.js', '/');
202+
} else if (this.manager.preset.name === reactTs.name) {
203+
testModule = this.manager.resolveModule('./src/setupTests.ts', '/');
204+
}
205+
} catch (e) {
206+
/* ignore */
207+
}
208+
209+
if (testModule) {
210+
await this.manager.transpileModules(testModule, true);
211+
this.manager.evaluateModule(testModule);
212+
}
213+
193214
// $FlowIssue
194215
const tests: Array<Module> = (await this.transpileTests()).filter(t => t);
195216

0 commit comments

Comments
 (0)