ES6 shorthand import
Asked Answered
W

4

29

Is there a shorter ES6 way of doing:

var assert = require('chai').assert;

than

import chai from 'chai';
var assert = chai.assert;

(chai is the chai-assertion library, in case you haven't heard of it yet.)

Wyeth answered 17/2, 2015 at 6:57 Comment(0)
H
40

Yes, you can do it like:

import { assert } from 'chai';

assert must be exporting from chai in that case. See spec here and about es6 modules here

Huoh answered 17/2, 2015 at 7:4 Comment(5)
How do you make it work? Node doesn't understand es6 by default :(Watercraft
@Watercraft use transpilers (for example babel with require hook babeljs.io/docs/usage/require). BTW Node (v8 more precisely) supports a lot of es6 features alreadyHuoh
If using mocha use "mocha --compilers <path to ts-node and register like node_modules/ts-node/register> name of filename.ts" after npm install ts-nodeTrait
I know this is an old post but for anyone searching - as of node v13 or higher you can put { "type": "module" } in your package.json to use ES6 import instead of babel or the experimental flags.Deflect
Kind of pointless as chai doesn't export assert like that. This answer will NOT work for chai (at least not in version 8).Spring
V
9

You can use it like this:

import * as chai from 'chai';

let assert = chai.assert;
let should = chai.should();
let expect = chai.expect;
Vital answered 29/10, 2015 at 7:44 Comment(0)
L
6

I'd rather:

import {assert, should, expect}  from 'chai';
Linebreeding answered 11/8, 2016 at 13:47 Comment(3)
It doesn't work for should: chaijs.com/guide/styles/#using-should-in-es2015 With your solution you'll have to use should().not.equal instead of should.not.equalGnosis
yeap, you just do: should('value1').not.be.equal('value2)Linebreeding
or expect('someValue').to.be.okLinebreeding
S
1

I use:

import chai from 'chai';
const { assert } = chai;
Sheave answered 17/1, 2021 at 18:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.