【问题标题】:How to make ChaiJS 'expect' function available in all files inside NodeJS 'test' folder?如何使 ChaiJS 'expect' 功能在 NodeJS 'test' 文件夹内的所有文件中可用?
【发布时间】:2018-02-26 10:17:01
【问题描述】:

我正在使用默认包含 Mocha 和 Chai 的 Truffle。

文件树:

├── test
│   ├── ManagedWallet.js
│   ├── AnotherTest.js
│   └── AndAnotherTest.js
└── truffle.js

这是我的测试文件之一:

var expect = require('chai').expect;
var managedWallet = artifacts.require("./ManagedWallet.sol");

contract('ManagedWallet', function(accounts) {

  it("belongs to customer's account address", async function(){
    var contract         = await managedWallet.deployed();
    var customer_account = accounts[1];
    var owner            = await contract.owner.call();

    expect(owner).to.equal(customer_account);
  });

});

由于test 文件夹中有很多测试文件,我需要将var expect = require('chai').expect; 行放在所有测试文件中。

有没有办法让expect 函数在全球范围内可用,而无需我在所有测试文件中都包含var expect = require('chai').expect; 行?

我尝试将 var expect = require('chai').expect; 行放入 truffle.js 文件中(module.exports 上方),但没有成功,并且在运行测试时出现 ReferenceError: expect is not defined 错误。

我的 truffle.js 文件示例(位于项目的根文件夹中):

module.exports = {

  networks: {
    development: {
      host: "127.0.0.1",
      port: 7545,
      network_id: "*" // match any network
    }
  }

};

【问题讨论】:

    标签: javascript node.js mocha.js chai truffle


    【解决方案1】:

    我从GitHub 得到了答案(感谢@keithamus)。

    require('chai/register-expect');
    
    //... rest of code
    expect(...)
    

    我的 truffle.js 看起来像:

    require('chai/register-expect');
    
    module.exports = {
      // the truffle configs
    }
    

    而且,在我的测试文件中使用expect 不再引发任何错误。 ?

    【讨论】:

      【解决方案2】:

      这是启用此功能的 .mocharc.json 文件:

      {
        "spec": "src/**/*.test.ts",
        "require": ["esm", "ts-node/register", "chai/register-assert", "chai/register-expect", "chai/register-should"],
        "file": "./test-setup.cjs",
        "recursive": true
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-03
        • 1970-01-01
        • 2019-08-07
        • 2021-04-30
        • 2018-09-16
        • 1970-01-01
        • 2018-04-02
        • 2011-02-24
        相关资源
        最近更新 更多