Chai: How to make expect/should/assert be global in test files and be able to pass eslint

Created on 23 Dec 2016  路  3Comments  路  Source: chaijs/chai

I use mocha/chai with eslint/flow.

Currently, I run the tests with an npm script:

"testonly": "babel-node ./node_modules/.bin/_mocha --require ./scripts/mocha-bootload --check-leaks --full-trace src/**/__tests__/**/*.test.js"

which will run ./scripts/mocha-bootload.js first to set expect global:

// ./scripts/mocha-bootload.js

var chai = require('chai');
chai.use(require('dirty-chai'));    // use dirty-chai to avoid eslint errors
global.expect = chai.expect;

...

Now I can use mocha/chai as global without importing them.

// ./src/__tests__/index.test.js
// no any import is needed
describe('first test', () => {
  it ('should be passed', () => {
    expect(true).to.be.true();
  })
})

But this will raise errors when I run eslint. To make mocha pass eslint, I add "env": {"mocha": true} in the .eslintrc config file:

// .eslintrc
{
  "env": {
    "mocha": true,
    ...
  },
  ...
}

However, it doesn't support "env": {"chai": true} to tell eslint treat chai as environment variables. How do I do to make it pass eslint (without adding any line in each test files)? By the way, is there any better way to set chia's expect/should/assert to be global?

Most helpful comment

Hey @xareelee, thanks for reaching out.

How do I do to make it pass eslint

You can specify "expect": true in ESLint's globals: http://eslint.org/docs/user-guide/configuring#specifying-globals

By the way, is there any better way to set chia's expect/should/assert to be global?

We are going to ship shiny new way of doing this (currently in master): https://github.com/chaijs/chai#pre-native-modules-usage-registers-the-chai-testing-style-globally

All 3 comments

Hey @xareelee, thanks for reaching out.

How do I do to make it pass eslint

You can specify "expect": true in ESLint's globals: http://eslint.org/docs/user-guide/configuring#specifying-globals

By the way, is there any better way to set chia's expect/should/assert to be global?

We are going to ship shiny new way of doing this (currently in master): https://github.com/chaijs/chai#pre-native-modules-usage-registers-the-chai-testing-style-globally

@shvaikalesh Great! Thanks for your reply, and it works for me. I'm looking forward to the next version of chai. 馃憤

@xareelee Me too. However, there are some issues that have to be resolved first: https://github.com/chaijs/chai/issues/890.

I will close this issue then. If you have another question or suggestion, please don't hesitate to open a new one.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ghost picture ghost  路  4Comments

huaguzheng picture huaguzheng  路  3Comments

liborbus picture liborbus  路  4Comments

sverrirs picture sverrirs  路  3Comments

meeber picture meeber  路  3Comments