Skip to content

Commit 37b1686

Browse files
authored
fix: prevent double teardown on test environment error (#15731)
1 parent c2b2faa commit 37b1686

File tree

5 files changed

+57
-2
lines changed

5 files changed

+57
-2
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
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+
import runJest from '../runJest';
9+
10+
// This test ensures that if a custom environment's teardown throws, Jest reports the real error, not an internal error.
11+
describe('Environment Teardown Error', () => {
12+
it('reports the error thrown from teardown() in a custom environment', () => {
13+
const {stderr, exitCode} = runJest('environment-teardown-error');
14+
expect(exitCode).toBe(1);
15+
expect(stderr).toMatch('teardown error from custom environment');
16+
// Should NOT contain the internal error that was seen in the regression
17+
expect(stderr).not.toMatch(
18+
'The "object" argument must be of type object. Received null',
19+
);
20+
});
21+
});
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/**
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
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+
const NodeEnvironment = require('jest-environment-node').default;
9+
10+
class EnvironmentWithTeardownError extends NodeEnvironment {
11+
async teardown() {
12+
await super.teardown();
13+
throw new Error('teardown error from custom environment');
14+
}
15+
}
16+
17+
module.exports = EnvironmentWithTeardownError;
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
/**
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
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+
'use strict';
8+
9+
test('Environment must tear down with a correct error stack trace', () => {});
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"jest": {
3+
"testEnvironment": "<rootDir>/EnvironmentWithTeardownError.js"
4+
}
5+
}

packages/jest-runner/src/runTest.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -217,8 +217,11 @@ async function runTestInternal(
217217
);
218218
sourcemapSupport.resetRetrieveHandlers();
219219

220-
await environment.teardown();
221-
isTornDown = true;
220+
try {
221+
await environment.teardown();
222+
} finally {
223+
isTornDown = true;
224+
}
222225
}
223226
};
224227

0 commit comments

Comments
 (0)