【问题标题】:How to prevent before and beforeEach in a file from applying to all tests in all files?如何防止文件中的 before 和 beforeEach 应用于所有文件中的所有测试?
【发布时间】:2017-01-18 13:27:29
【问题描述】:

我已经使用 mocha 自动化了我的 api。 结构是-

1.对于每个 api,都有一个 api_namex.js 文件,mocha 测试所在的文件

  1. 每个 api_namex.js 文件都有一个 describe() 和多个 it()describe()

  2. 现在,如果我在 api_namex.js 文件之一(比如 api_name1.js)中使用 beforeEach(),那么在运行整个测试套件时,涉及运行所有 api_namex.js 文件,beforeEach() 被所有这些文件调用

我应该如何让它只为预期的 api_namex.js 文件运行? 之前也有同样的问题。

my_areas.js 文件附在下面。我在这里使用了 beforeEach()。但是在运行整个测试套件时,这个 beforeEach 在每个测试用例之前都会被调用。我想要它只在这个 describe() 内的每个测试用例之前

var should = require('should'),
    supertest = require('supertest'),
    servicesGenerator = require('../../utils/services_generator_test.js'),
    responseMsg = require('../../utils/response_messages.js'),
    helper = require('../../utils/helper.js'),
    testData = require('../../utils/test_data.js'),
    apiEndPoints = require('../../utils/api_endpoints.js');

beforeEach(function (done) {
    clearMyAreas();
    done();
});

describe('My Areas', function () {

    it('1: All Data Valid', function (done) {
        servicesGenerator.postPlayoApi(apiEndPoints.myAreas)
            .send(getValidMyAreasBody())
            .end(function (err, res) {
                baseValidator(err, res, 1, responseMsg.myAreasSuccess);
                areasValidator(err, res, 1);
                done();
            });
    });

    it('2: Invalid userId', function (done) {
        servicesGenerator.postPlayoApi(apiEndPoints.myAreas)
            .send(getValidMyAreasBody(testData.userIdInvalid))
            .end(function (err, res) {
                baseValidator(err, res, 0, responseMsg.invalidUserId);
                done();
            });
    });
   });

【问题讨论】:

  • 如果您希望 beforeEach 仅用于描述中的 its,请将 beforeEach 也移动到描述中。否则,您可以嵌套描述,如果您希望相同的 beforeEach 覆盖其中的几个,那么它们可能足够相关,您也可以将它们描述为一个组

标签: javascript mocha.js


【解决方案1】:

查看文档,您应该能够将 beforeEachbefore 钩子放在 describe 块中,它们应该在 describe 的上下文中运行:https://mochajs.org/#hooks

【讨论】:

    猜你喜欢
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 2013-02-11
    • 2013-11-22
    • 2020-09-13
    • 2018-07-25
    • 2022-12-09
    • 2011-05-02
    相关资源
    最近更新 更多