【问题标题】:How do I write mocha tests where one tests depends on the result for the next test?我如何编写摩卡测试,其中一个测试取决于下一个测试的结果?
【发布时间】:2014-02-11 14:10:55
【问题描述】:
describe("Company Controller", function() {
  var apiUrl;

  beforeEach(function(done) {
    apiUrl = "http://localhost:3001";

    done();
  });

  it('should register a client without error and return an API key', function(done) {
    request({
      uri: apiUrl + '/api/v1/company',
      method: 'POST',
      json: true,
      form: {
        name: 'My Company'
      }
    }, function(err, res, body) {
      should.not.exist(err);
      res.statusCode.should.eql(200);
      body.status.should.eql('ok');
      should.exist(body.company.api_key);
      done();
    });
  });

  it('should generate a new API key for a company', function(done) {
    // NEED THE client_id generated in the previous test

  });

  after(function(done) {
    Company.remove().exec();
    done();
  });
});

接下来的测试如何获取client_id?

【问题讨论】:

    标签: node.js unit-testing express mocha.js


    【解决方案1】:

    一般来说,制作带有副作用的测试是一种脆弱的做法。经常这样做,您将开始遇到一些非常难以调试的错误,即使每个测试都单独运行,您的测试套件也会失败,并且错误消息不会有任何帮助。理想情况下,每个测试都应该“离开营地”时保持与找到它时相同的状态。

    如果你真的坚持这样做,你当然可以设置一个全局变量。其他一些选项包括:

    • 合并两个测试。是的,这违反了某些人持有的 Single-Assertion-Per-Test 原则,但我认为避免副作用原则胜过该原则。

    • 将注册放在 beforeEach 函数中。是的,通过这样做,您将在每个测试套件运行时注册多个客户端。这仍然是我的首选方法。

    【讨论】:

    • 我喜欢将注册放在beforeEach,但是我如何测试注册是否发生?
    • beforeEach 可以设置一些变量(类似于它设置 apiUrl 的方式)。这些变量可以在第一个基本测试中被断言,然后被其他测试使用。或者,许多测试框架(可能包括 Mocha)将允许您在 beforeEach 中运行断言。因此,您可以将这些基本断言作为 beforeEach 的一部分运行,甚至不需要对它们进行单独的测试。
    【解决方案2】:

    您应该使用存根。例如sinonjs。这样你就可以使用一个假函数来测试另一个函数。如果您只需在 it 函数中定义函数后对函数进行存根,则无需使用 beforeEachafterEach

    describe("Company controller", function() {
      describe("dependantFunction()", function() {
        var stub;
    
        beforeEach(function() {
          stub = sinon.stub(module, 'targetFunction');
    
          stub.onCall(0).callsArgWith(1, ...some valid results...);
          stub.onCall(1).callsArgWith(1, ...some expected error...);
          stub.throws();
        });
    
        afterEach(function() {
          stub.restore();
        });
    
        it("should do something", function() {
           var result;
    
           module.targetfunction(null, result);
           dependantfunction(result);
           ....your tests here....
        });
    
        it("should do something else", function() {
          ...
        });
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多