从未按预期工作的承诺返回的数组解构

Array destructuring returned from promises not working as expected

我正在使用 Mocha and Chai 为部署在带有 truffle 的开发区块链上的智能合约编写测试。

我有一个名为 Election 的合同,其中包含两个候选人。

测试代码如下:

it("Checking the properties for candidates", () => {
    return Election.deployed().then((app) => {
      return [app.candidates(1), app];
    }).then(params => {
      const [candidate1, app] = params;
      assert.equal(candidate1.id, 0);
      return [app.candidates(1), app];
    }).then(params => {
      const [candidate2, app] = params;
      assert.equal(candidate2.id, 1);
    });
  });

当我没有使用数组解构到 return app.candidates()app 的实例时,测试用例通过了。在那种情况下,我必须声明一个全局变量,将其分配给 app 并在每个范围内使用它。但我想避免定义一个全局变量。我在 SO 上遇到了 post,它建议使用 ES6 解构。

但在这里我得到的 candidate1.idcandidate2.id 都是 undefined

我做错了什么?

你为什么要从 it 回来?不需要,他们应该只扔。

我强烈建议避免这种 .then 语法,npm i chai-as-promised --save-dev 然后像这样安装它:

const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');

// Must install Chai as Promised last - https://github.com/domenic/chai-as-promised/#node
chai.use(chaiAsPromised);

// Disable object truncating - 
chai.config.truncateThreshold = 0;

global.expect = chai.expect;

那么你会做:

it("Checking the properties for candidates", async () => {
    expect(Election.deployed()).to.eventually.satisfy(app => app.candidates(1).id === 0)
        and.satisfy(app => app.candidates(2).id === 1);
});

如果 app.candidates returns 一个承诺,也许甚至可以做到这一点,不过我不确定 satisfy 参数的异步函数。

it("Checking the properties for candidates", async () => {
    expect(Election.deployed()).to.eventually.satisfy(async app => {
        await expect(app.candidates(1)).to.eventually.be.an('object').that.has.property('id', 0);
        await expect(app.candidates(2)).to.eventually.be.an('object').has.property('id', 1);
    });
});