Jest中如何先验证对象初始化再基于该对象动态生成test.each测试用例?
Solution
The core challenge here is that Jest parses all test definitions upfront (before any test code runs), so you can't dynamically generate tests based on an object initialized inside a test case directly. However, we can work around this by initializing the object during the describe block setup (before tests execute) and using a try/catch to handle initialization errors, then conditionally generating tests based on whether the initialization succeeded.
Here's how to implement this properly:
class mock { constructor(a, b, c) { this.a = a; this.b = b; this.c = c; // Simulate random fatal error for testing (remove in production) if (Math.random() < 0.2) { throw new Error("Random initialization failure!"); } } getFunNames() { return ["funNameA", "funNameB", "funNameC"]; } funNameA() { return this.a; } funNameB() { return this.b; } funNameC() { return this.c; } } describe('Mock Class Validation', () => { let value; let funNames; let initError; let succeededTests = 0; // Attempt initialization during describe setup (before tests run) try { value = new mock(1, 2, 3); funNames = value.getFunNames(); } catch (err) { initError = err; } // First test: Verify initialization succeeded test('Object initializes without fatal errors', () => { expect(initError).toBeUndefined(); if (initError) { console.error('Initialization error details:', initError); } }); // Conditionally generate method tests only if initialization worked if (!initError) { const totalTests = funNames.length; funNames.forEach(methodName => { test(`Method ${methodName} executes without throwing`, () => { expect(() => { value[methodName](); succeededTests++; }).not.toThrowError(); }); }); // Final test: Ensure all method tests passed test('All method tests completed successfully', () => { expect(succeededTests).toBe(totalTests); }); } else { // Skip method tests if initialization failed test.skip('Skipping method tests: Initialization failed', () => {}); } });
Key Details:
- Initialization During Describe Setup: We initialize the object inside the
describeblock (not inside a test case) but wrap it in a try/catch. This lets us capture any fatal initialization errors without crashing the entire test suite. - Initialization Validation Test: The first test explicitly checks that initialization succeeded. If it failed, this test will fail, and we can log the error details for debugging.
- Conditional Test Generation: We only generate the method-specific tests if initialization was successful. If not, we skip those tests to avoid unnecessary failures.
- Success Count Verification: We track successful method tests and verify the count matches the total number of methods in the final test, just like your original code intended.
Why This Works:
- Jest runs the
describeblock code before executing any tests, so we can safely initialize the object here and capture errors. - By conditionally generating tests based on the initialization result, we avoid trying to run tests against an uninitialized object.
- All errors (both initialization and method execution) are captured as Jest test failures, with full logging available in your test output.
内容的提问来源于stack exchange,提问作者Elley
相关产品推荐
相关产品推荐

