草庐IT

javascript - 在多个文件中拆分 mocha API 测试

coder 2024-07-26 原文

我正在为我正在构建的产品构建一些 API 测试。其中一个测试如下所示:

GET FILTERS
  ✓ should be restricted (45ms)
  it should get the filters
    ✓ should return 200
    ✓ should return an object
    ✓ should close db connections
GET USERS COUNT
  ✓ should be restricted
  ✓ should throw error when payload is not correct
  it should get the user count
    ✓ should return 200
    ✓ should return an object
    ✓ should close db connections
GET USERS FILE
  ✓ should be restricted
  ✓ should throw error when no queryId is specified
  it should retrieve the file
    ✓ should return 200
    ✓ should download an excel file
    ✓ should close db connections
UPLOAD PROMOTION IMAGE
  ✓ should throw error when no file is specified
  it should save the file
    ✓ should return 200
    ✓ should have named the file with the title of the promotion
    ✓ should have uploaded the file to S3 (355ms)
    ✓ should close db connections
CREATE PROMOTION
  it should save the promotion
    ✓ should return 200
    ✓ should return a correct response
    ✓ should close db connections
GET PROMOTIONS
  ✓ should be restricted
  it should get the promotions
    ✓ should return 200
    ✓ should be an array of promotions
    ✓ should contain the previously created promotion
UPDATE PROMOTION
  it should update the promotion
    ✓ should return 200
    ✓ should return a correct response
    ✓ should close db connections
PUT PROMOTION IN BIN
  it should put the promotion in the bin
    ✓ should return 200
    ✓ should return a correct response
    ✓ should close db connections
GET ARCHIVED PROMOTIONS
  ✓ should be restricted
  it should get the promotions
    ✓ should return 200
    ✓ should be an array of promotions
    ✓ should be an array of archived promotions
    ✓ should contain the previously archived promotion
DELETE PROMOTION
  it should delete the promotion
    ✓ should return 200
    ✓ should return a correct response
    ✓ should have deleted the file from S3 (563ms)
    ✓ should close db connections

如您所见,我已尝试将与促销有关的所有内容都放在一个测试套件中,这样我就可以有一种工作流程来测试用户将在平台上做什么。

在这个例子中,我创建了一个随机生成的促销事件,然后使用该促销事件的 ID 来读取它、更新它、存档它,最后删除它。每一步都是相连的,我需要为每套西装返回值(即:插入的促销 ID 或过滤器......)

此时我的 promotions.test.js 文件是 625,由于我还没有完成,我希望它在接下来的几天内增长很多。

有没有一种方法可以将多个测试套件拆分到不同的文件中,但每个测试/文件都能在完成后立即返回一个我可以传递给下一步的值?

赏金编辑

目前我只尝试过这样的事情:

describe.only("Gifts Workflow", function() {

var createdGift;
describe("CREATE", function() {
    require("./GIFTS/CREATE.js")().then(function(data) {
        createdGift = data;
    });
});

describe("READ FROM WEB", function() {
    require("./GIFTS/READ FROM WEB.js")(createdGift).then(function(data) {

    });
});
});

“./GIFTS/CREATE.js”的内容

module.exports = function() {
return new Promise(function(resolve, reject) {

    //DO SOME TESTS WITH IT AND DESCRIBE

    after(function() {
        resolve(createdGift);
    });
});

};

问题是测试会立即由 mocha 初始化,因此在第二个测试套件“READ FROM WEB”中,作为 createdGift 传递的值会立即提供给测试,而无需等待第一个测试完成,因此传递了 undefined .

Jankapunkt 的回答

这是我在代码中尝试的方式:

var create = require("./GIFTS/CREATE");
var read = require("./GIFTS/READ FROM WEB");

describe.only("Gifts Workflow", function() {
    create(function(createdGift) {
        read(createdGift);
    });
});

创建

module.exports = function(callback) {
        var createdGift;

        //SOME TESTS

        describe("it should insert a gift", function() {

            var result;
            before(function() {
                return request
                    .post(url)
                    .then(function(res) {
                        createdGift = res.body;
                    });
            });

      //SOME OTHER TESTS

        });


        after(function() {
            callback(createdGift);
        });
};

从网络阅读

module.exports = function(createdGift) {
    it("should be restricted", function(done) {
        request
            .get(url)
            .query({})
            .end(function(err, res) {
                expect(res.statusCode).to.equal(400);
                done();
            });
    });

    describe("it should read all gifts", function() {
           //SOME TESTS
    });
};

这是输出

Gifts Workflow
  ✓ should be restricted
  ✓ should not work when incomplete payload is specified
  it should insert a gift
    ✓ should return 200
    ✓ should return an object
    ✓ should have uploaded the image to S3 (598ms)
    ✓ should close db connections

it should read all gifts
  ✓ should return 200
  ✓ should return an array
  ✓ should contain the previously added gift
  ✓ should close db connections


10 passing (3s)

它可能看起来有效,但正如您从表格中看到的那样,它应该读取所​​有礼物 不是 Gifts Workflow 的子项,而是根套件的子项.

是这样的:

  1. Mocha 调用根套件
  2. Mocha 找到Gifts Workflow 套件并在该套件中执行 create() 函数
  3. 由于函数是异步的,Mocha 认为 Gifts Workflow 套件已结束并返回到根套件
  4. read() 被执行
  5. Mocha 退出根套件并进入下一个测试,因为它是异步的,它认为所有测试都已完成
  6. 测试 #3,4,5,... 从未被调用

您能否通过两次以上的测试确认这也是您的情况?

最佳答案

我正在处理类似的问题,我至少找到了解决方法。如果有什么不对,请发表评论。

我想出了这个,当我发现时,mocha 只会自动执行 describe block ,当它们在模块范围内但不在函数内时。

它分解为以下方法:

  • 将所有 describe block 包装在由您的模块导出的函数中
  • 将回调传递给提供返回值的函数
  • 在测试套件中使用回调按顺序调用函数

可重现的例子

创建最小测试设置

index.js
test1.js
test2.js

在您的测试文件中,您将测试包装在导出的函数中。请注意,我使用 ES6 导入/导出模块。

test1.js

export const test1_method = function(callback){

    let returnValue; // declared outside the tests

    describe("test 1", function(){


        it ("1. unit", function(){
            assert.isTrue(true);
            // assigned inside test
            returnValue = 42; 
        });

        it ("2. unit", function(){
            assert.isTrue(true);
            callback(returnValue); // called in the last unit
        });

    });
}

如您所见,此函数传递了一个简单的回调,并在最后一个单元中调用。你可能会争辩说,这是非常模糊的。我同意,但实际上我从未在描述 block 中看到 it-units 的序列随机性。因此您可以假设,回调将在您的最后一个单元运行后被调用。

test2.js

export const test2_method = function(previousValue){

    describe("test 2", function(){

        it ("runs correctly with a dependency value", function(){
            assert.equal(previousValue, 42);
        })
    })

}

这里没有太多要添加的,只是接受输入并测试特定值。

index.js

import {test1_method} from './test1.js';
import {test2_method} from './test2.js';


test1_method(function(test1Result){
    // run the other tests in the callback
    test2_method(test1Result);
});

在这里,您可以将测试粘合在一起。这将是您套件的根目录。您调用第一个方法并提供回调,最终将结果传递给 test2 方法。令人惊讶的是,第一个测试的结果并非未定义,您可以轻松地将其作为参数传递给 test2。

输出

I20170515-15:09:33.768(2)?   test 1
I20170515-15:09:33.769(2)? 
I20170515-15:09:33.770(2)?     ✓ 1. unit
I20170515-15:09:33.770(2)? 
I20170515-15:09:33.771(2)?     ✓ 2. unit
I20170515-15:09:33.771(2)? 
I20170515-15:09:33.772(2)?   test 2
I20170515-15:09:33.773(2)? 
I20170515-15:09:33.773(2)?     ✓ runs correctly with a dependency value

优势

您可以控制您的测试顺序并将您的套件拆分为子套件。

您编写参数化测试,这也使它们可重用,具体取决于用例。例如,在我的测试套件中有一个函数带有一组 10 个测试的描述,它适用于我所有的 mongo 集合。

缺点

您需要将所有测试重写为包装函数,以便 mocha 不会自动执行任何测试,而只会由您的测试套件自动执行。

回调中的多个回调使其难以阅读和调试。

总结

在我看来,这不是“官方”解决方案,而是一种变通方法,如果找不到其他解决方案,您可以从中改进测试服。

关于javascript - 在多个文件中拆分 mocha API 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43836993/

有关javascript - 在多个文件中拆分 mocha API 测试的更多相关文章

  1. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  2. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  3. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  4. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  5. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  6. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  7. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  8. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  9. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  10. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

随机推荐