Last active
July 1, 2021 10:30
-
-
Save mrister/505700e6d27e2ff0a7aa8962fd911111 to your computer and use it in GitHub Desktop.
Mocha and chai example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# make soure you have mocha installed | |
npm i mocha -g | |
# run tests with mocha | |
mocha --reporter=spec test.spec.js |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var chai = require('chai'); | |
var expect = chai.expect; | |
var assert = chai.assert; | |
var testObj = { | |
name: "test", | |
sub: { | |
name: 'test sub' | |
}, | |
numbers: [1, 2, 3, 4], | |
hasNumbers : true | |
}; | |
describe ('Test Suite', function () { | |
describe('expect tests', function () { | |
it ('should be a valid testObject', function () { | |
expect(testObj).to.be.an('object').and.is.ok; | |
expect(testObj).to.have.property('sub').that.is.an('object').and.is.ok; | |
expect(testObj.sub).to.have.property('name').that.is.a('string').and.to.equal('test sub'); | |
expect(testObj).to.have.property('numbers').that.deep.equals([1, 2, 3, 4]); | |
expect(testObj).to.have.property('hasNumbers', true); | |
}); | |
}); | |
describe('assert tests', function () { | |
it ('should be a valid testObject', function () { | |
assert.isOk(testObj); | |
assert.isObject(testObj); | |
assert.propertyVal(testObj, 'name', 'test'); | |
assert.property(testObj, 'sub'); | |
assert.propertyVal(testObj.sub, 'name', 'test sub'); | |
assert.deepEqual(testObj.numbers, [1, 2, 3, 4]); | |
assert.typeOf(testObj.hasNumbers, 'boolean'); | |
assert.isTrue(testObj.hasNumbers); | |
}); | |
}); | |
}); |
@mrister, while globals might be confusing for someone who's coming to the project to figure out where those variables are coming from, a config file sounds cool, thank you!
@lonely-cat. Yes that might be true, bit a little bit of documentation in project/s readme goes long way ;-). Glad to help!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@lonely-caat, That depends on your setup and test runner however you could try as described here and register them as globals chaijs/chai#1140 (comment)
A quite common approach if you are using mocha is to set up a mocha.opt or .mocharc config file and in it require a module where you import chai (and any other helpers you would like) and then those are globally available for usage in test files
https://github.com/mochajs/mocha/blob/master/example/config/.mocharc.js#L34