【问题标题】:can jest output console log within test block output可以在测试块输出中开玩笑输出控制台日志
【发布时间】:2019-04-01 23:00:41
【问题描述】:

因此,如果我将 console.log 放入 test 中,则 console.log 将在测试后出现,例如

  authentication.spec.js
    register
      ✓ should be able to insert (128ms)
      ✓ should fail because of duplicate (100ms)
      ✓ should have user id assigned (1ms)
    login
      ✓ should be able to login for correct user (117ms)
      ✓ should fail for incorrect user (14ms)

  console.log tests/unit/authentication.spec.js:110
    we can see a message

我想看到的是这样的:

  authentication.spec.js
    register
      ✓ should be able to insert (128ms)
      ✓ should fail because of duplicate (100ms)
      ✓ should have user id assigned (1ms)
    login
      ✓ should be able to login for correct user (117ms)
        console.log tests/unit/authentication.spec.js:110
           we can see a message
      ✓ should fail for incorrect user (14ms)

所以在这种情况下console.log 应该与✓ should be able to login for correct user 一起出现

当我使用 Mocha 时,我使用的是 mocha-logger

【问题讨论】:

标签: javascript testing jestjs


【解决方案1】:

据我所知,这并不容易,尽管有几个地方可以查找更多信息(不是开箱即用的):

Jest 允许使用自定义报告器:https://jestjs.io/docs/en/configuration.html#reporters-array-modulename-modulename-options,因此您可以编写自己的报告器并以不同的方式显示输出。目前,虽然您没有获得单独测试的更新,只是测试套装,这是 Dan Abramov 创建的一个问题:https://github.com/facebook/jest/issues/6616

从上面的 github 线程 - Reporter 界面现在看起来像:

export default class BaseReporter {
  onRunStart(results: AggregatedResult, options: ReporterOnStartOptions) {}

  // these are actually for the test suite, not individual test results
  onTestStart(test: Test) {}
  onTestResult(test: Test, testResult: TestResult, results: AggregatedResult) {}

  onRunComplete(contexts: Set<Context>, results: AggregatedResult ): ?Promise<void> {}
}

我没有找到将参数从测试传递到testResult 对象的预定义方法。因此,您主要限于基于测试名称记录信息。以下是testResult 对象内的testResult 属性示例:

testResults:
  [ { ancestorTitles: [Array],
       duration: 5,
       failureMessages: [],
       fullName: 'add should add two numbers',
       location: null,
       numPassingAsserts: 0,
       status: 'passed',
       title: 'should add two numbers' } ],

如您所见,这是记者使用的所有信息标准:测试名称、持续时间、状态。作为参考,默认记者在这里:https://github.com/facebook/jest/blob/7b7fd01350/packages/jest-cli/src/reporters/default_reporter.js

【讨论】:

  • 我认为问题与测试覆盖率报告无关。我们也可以得到覆盖率报告,但测试用例中的控制台日志必须以不同方式处理。
【解决方案2】:

是的,您可以将其记录下来。您可能需要将--verbose false 添加到package.json "test";

例如:"scripts": { "test": "jest --watch --verbose false" }

See the details here at github for jest bugs

【讨论】:

    【解决方案3】:

    我用这个:

    // package.json

    ...
        "scripts": {
            ...
            "test": "react-scripts test --verbose=true",
            ...
        }
    ...
    

    在控制台中,它看起来像......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-07
      • 2019-10-06
      • 2017-11-22
      • 1970-01-01
      • 1970-01-01
      • 2019-01-08
      • 1970-01-01
      相关资源
      最近更新 更多