【问题标题】:Externally determine which test cases fail - Javascript从外部确定哪些测试用例失败 - Javascript
【发布时间】:2020-02-08 12:09:06
【问题描述】:

我正在解决一个问题,当该应用程序的测试套件运行时,我需要检测任何 javascript/node.js 应用程序的哪些测试用例失败。我需要以编程方式确定这一点。

Mocha testsuite output result

考虑上面的测试输出示例,对于这个示例,我想编写一个外部 javascript 脚本,它可以告诉我哪个特定的测试用例失败了。

目前我想到的唯一解决方案是;在 javascript 子进程中执行 npm test 并从 stdout 流中读取其输出,解析输出并提取必要的信息,就像这样。

const { spawn } = require('child_process');
const chalk = require('chalk');
const child = spawn('npm.cmd',['test']);

line = 0
child.stdout.on('data', (data) => {
  console.log(`${chalk.bgBlue('line = ' + line)} , data = ${data}`);
  line++;
});

但是,这将是一种非常严格的方法。我想要一种更通用的方法,它可以适用于各种测试模块(不仅仅是 mocha)。

我们将不胜感激!

【问题讨论】:

    标签: javascript unit-testing testing mocha.js


    【解决方案1】:

    您可以在执行到代码后为每个测试获取state。这样你就可以知道测试是否通过了。

    您需要的代码非常简单。像这样的:

    afterEach(function () {
            const state = this.currentTest.state;
            if (state !== "passed") {
                //Do whatever you want with this value
            }
        });
    

    例如,如果你想存储到代码中,哪个测试失败了,那么你可以这样编码:

    var testFailed = []
    describe('test', function () {
    
        afterEach(function () {
            const state = this.currentTest.state;
            if (state !== "passed") {
                testFailed.push(this.currentTest.title)
            }
        });
    
        after(function(){
            console.log(testFailed)
        })
    
        it('test1', () => {
            assert.equal(1, 1)
    
        });
        it('test2', () => {
            assert.equal(1, 2)
        });
    })
    
    

    输出将是:

      test
        √ test1       
        1) test2      
    [ 'test2' ]       
    
    
      1 passing (15ms)
      1 failing
    

    现在你可以玩这个了。您可以使用该变量来完成您的工作,甚至可以创建一个文件或任何您想要存储信息的东西。

    【讨论】:

      猜你喜欢
      • 2010-11-27
      • 1970-01-01
      • 2019-11-11
      • 1970-01-01
      • 2014-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-29
      相关资源
      最近更新 更多