0

以下测试是执行此操作的最佳方法,还是我可以改进它(并删除 Step 依赖项)?

我特别担心每个“步骤”函数都将前一次执行的测试与下一次执行的调用混为一谈。(即剪切粘贴易碎)

(另请参阅:如何按顺序执行异步 Mocha 测试(NodeJS)?

  it('should run an update', function(done) {
    var db = new database.Database();
    var sess = new session.Session(db);
    Step(
      function createTable() {
        sess.exec('create table customers (id integer primary key auto_increment, name varchar, age integer)', this);
      },
      function insertCustomer1(err, message) {
        assert(!err, err);
        assert.equal("Table created.", message);
        sess.exec('insert into customers (name, age) values ("james", 41)', this);
      },
      function insertCustomer2(err, message) {
        assert(!err, err);
        assert.equal("1 row inserted.", message);
        sess.exec('insert into customers (name, age) values ("thomas", 19)', this);
      },
      function updateCustomer1(err, message) {
        assert(!err, err);
        assert.equal("1 row inserted.", message);
        sess.exec('update customers set age = 42 where name = "james"', this);
      },
      function end(err, message) {
        assert(!err, err);
        assert.equal("1 row updated.", message);
        done();
      }

    );
  });
4

1 回答 1

1

要解决合并问题,您可以编写如下代码:

Step(
  function createTable() {
    var next = this;
    sess.exec('create table customers (id integer primary key auto_increment, name varchar, age integer)', function (err, message) {
      assert(!err, err);
      assert.equal("Table created.", message);

      next();
    });
  },
  function insertCustomer1() {
    var next = this;
    sess.exec('insert into customers (name, age) values ("james", 41)', function (err, message) {
      assert(!err, err);
      assert.equal("1 row inserted.", message);

      next();
    });
  },

我相信您需要设置var next = this,因为 Stepthis用作异步步骤的回调,并且在对 sess.exec 的调用中不会正确绑定。如果那是一个交易破坏者(在我看来,样板文件越少越好),您可能会考虑使用async#series

于 2012-12-19T19:40:29.993 回答