You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jasmine中将测试用例执行结果记录到JSON日志文件?

How to Write Jasmine Test Results to a JSON File in afterAll

Hey there! Since you're new to Jasmine and want to capture test execution results and write them to a JSON file using the afterAll hook, let me walk you through a straightforward, working approach.

The Core Idea

Jasmine provides a custom reporter API that lets you hook into different stages of test execution (like when a test starts, finishes, or a suite completes). We'll use this to collect all test results first, then write them to a JSON file in the afterAll hook.

Full Working Code Example

Here's how to modify your existing code to achieve this (note: this assumes you're running Jasmine in a Node.js environment, which is standard for generating reports):

const fs = require('fs');

// Initialize an object to store all test results
const testResults = {
  executionTimestamp: new Date().toISOString(),
  testSuites: []
};

// Add a custom Jasmine reporter to collect results
jasmine.getEnv().addReporter({
  // Triggered when a test suite starts
  suiteStarted: function(suiteResult) {
    testResults.testSuites.push({
      suiteName: suiteResult.description,
      testCases: []
    });
  },
  // Triggered when a single test case finishes
  specDone: function(testResult) {
    // Get the current active test suite
    const currentSuite = testResults.testSuites[testResults.testSuites.length - 1];
    // Add test case details to the suite
    currentSuite.testCases.push({
      testName: testResult.description,
      status: testResult.status, // "passed", "failed", or "pending"
      failedAssertions: testResult.failedExpectations.map(expectation => ({
        message: expectation.message,
        stackTrace: expectation.stack
      }))
    });
  }
});

// Your existing test code
describe("Sample test 1", function(){
  it("after each function ", function(){
    expect(1).toEqual(1);
  });
  it("Sample test 2 ", function(){
    expect(1).toEqual(1);
  });
});

// Write results to JSON file after all tests complete
afterAll(function(){
  // Convert results to a formatted JSON string
  const jsonOutput = JSON.stringify(testResults, null, 2);
  // Write to file (use fs.writeFile for async if needed)
  fs.writeFileSync('jasmine-test-results.json', jsonOutput);
  console.log('Test results successfully saved to jasmine-test-results.json');
});

Breakdown of Key Parts

  • fs Module: We use Node.js's built-in file system module to write the JSON file to disk.
  • Result Collection: The custom reporter listens to suiteStarted (to track new test suites) and specDone (to capture each test case's outcome, including failures).
  • afterAll Hook: Once all tests finish, we convert the collected results into a human-readable JSON string and write it to a file.

Extra Tips

  • If you need more details (like suite duration, total passed/failed counts), you can extend the reporter to listen to other events like suiteDone or jasmineDone.
  • For asynchronous file writing, replace fs.writeFileSync with fs.writeFile (remember to add a callback or use async/await since afterAll supports asynchronous functions).

内容的提问来源于stack exchange,提问作者NarendraR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:43:28