如何为多个需求模块设置单元测试

How to setup unit testing for multiple require module

本文关键字:模块 设置 单元测试 需求      更新时间:2023-09-26

我正在开发一个代码库,其中代码被划分为多个需求模块。即每个部分都有自己的main.js,具有所需的配置。

我想使用Karma为整个代码库设置代码覆盖范围。

由于每个部分都有自己的requirejs配置,我为每个模块创建了一个test-main.js。

并让karma.config加载所有的test-main.js文件。

我遇到了一些问题。baseUrl之间存在冲突。

当只测试一个模块时,它运行良好。

知道吗?

您可以通过编程方式使用因果报应来链接多个因果报应运行器。Karma提供了一个API,使其以编程方式工作(这并不是很清楚IMHO——一些例子可以改进它)。

首先,您需要一个配置数组,然后您需要以编程方式调用karma并连锁调用。

创建配置阵列

function getConfiguration(filename){
  return {
    // you can enrich the template file here if you want
    // e.g. add some preprocessor based on the configuration, etc..
    //
    // if not set in the config template 
    // make Karma server launch the runner as well
    singleRun: true,
    // point to the template
    configFile : __dirname + filename
  };
}
function createConfigurations(){
    return [getConfiguration('conf1.js'), getConfiguration('conf2.js'), etc...];
}

以编程方式启动因果报应

function startKarma(conf, next){
  karma.server.start(conf, function(exitCode){
    // exit code === 0 is OK
    if (!exitCode) {
      console.log(''tTests ran successfully.'n');
      // rerun with a different configuration
      next();
    } else {
      // just exit with the error code
      next(exitCode);
  }
});

锁住因果报应的跑步者

// Use the async library to make things cleaner
var async = require('async');
var karma = require('karma');
var confs = createConfigurations();
async.eachSeries(confs, startKarma, function(err){
  if(err){
    console.log('Something went wrong in a runner');
  else {
    console.log('Yay! All the runners have finished ok');
  }
});