How to use chai

Comprehensive chai code examples:

How to use chai.isUndefined:

15
16
17
18
19
20
21
22
23
  it('Should return an empty object for an empty string input.', () => {
    assert.deepEqual(letterPositions(''), {});
  });


  it('Should return undefined for a letter not in the input string.', () => {
    assert.isUndefined(letterPositions('hello')['s']);
  });
});

How to use chai.isNull:

54
55
56
57
58
59
60
61
62
    .then(
      () => {
        // should fail
      },
      () => {
        assert.isNull(RED.node.message());
        assert.equal(RED.node.error(), 'Node "message" is not supported by unknown transport');
      });
});

How to use chai.should:

2
3
4
5
6
7
8
9
10
11
12
13
14
const SpendingLimit = require("../models/spendingLimitModel");


const {flushDB, assertError, generateToken} = require("./utils");


const chai = require("chai");
const should = chai.should();


const chaiHttp = require("chai-http");
const app = require("../app");

How to use chai.oneOf:

202
203
204
205
206
207
208
209
210
211
  });
  MessageBlock(RED);
  RED.node.get().emit('input', msg);
  return RED.node.get().await()
    .then(() => {
      assert.oneOf(RED.node.message().payload.content, ['Message 1', 'Message 2', 'Message 3']);
    });
});

/*it('should have even distribution for a randomly picked message', function() {

How to use chai.isObject:

147
148
149
150
151
152
153
154
155
156
ContextBlock(RED);
RED.node.get().emit('input', msg);
return RED.node.get().await()
  .then(() => {
    assert.equal(RED.node.message().payload.type, 'intent');
    assert.isObject(RED.node.message().payload.variables);
    assert.equal(RED.node.message().payload.variables.variable1, 'one');
    assert.equal(RED.node.message().payload.variables.variable2, 42);
    assert.equal(RED.node.message().payload.variables.variable3, true);
    assert.equal(msg.chat().get('variable1'), 'one');

How to use chai.spy:

27
28
29
30
31
32
33
34
35
36
  loadGrammarSync('python.cson');
  loadGrammarSync('python-regex.cson');
});

afterEach(() => {
  chai.spy.restore(console, 'error')
  chai.spy.restore(grammar, 'getMaxTokensPerLine')
})

describe("when the registry is empty", () => {

How to use chai.deepEqual:

0
1
2
3
4
5
6
7
8
9
10
const letterPositions = require('../letterPositions');
const assert = require("chai").assert;


describe('#letterPositions', () => {
  it('Should return an object with the indices of each letter in the input string', () => {
    assert.deepEqual(letterPositions('hello'), { h: [0], e: [1], l: [2, 3], o: [4] });
  });
  
  it('Should return the correct indices for a given letter.', () => {
    assert.deepEqual(letterPositions('hello')['h'], [0]);

How to use chai.include:

94
95
96
97
98
99
100
101
102
103
function shouldContain(shouldOrNot, expected, expectedReprompt) {
  test.checks.push((testCase) => {
    const actuals = getActuals(testCase);
    if (paramPassed(expected)) {
      it(`Alexa's ${type} response should ${not(shouldOrNot)}contain: ${expected}`, () =>
        shouldOrNot ? assert.include(actuals.speech, expected) : assert.notInclude(actuals.speech, expected)
      );
    }
    if (paramPassed(expectedReprompt)) {
      it(`Alexa's ${type} reprompt should ${not(shouldOrNot)}contain: ${expectedReprompt}`, () =>

How to use chai.match:

111
112
113
114
115
116
117
118
119
120
function shouldMatch(shouldOrNot, regex, regexReprompt) {
  test.checks.push((testCase) => {
    const actuals = getActuals(testCase);
    if (paramPassed(regex)) {
      it(`Alexa's ${type} response should ${not(shouldOrNot)}match: ${regex}`, () =>
        shouldOrNot ? assert.match(actuals.speech, regex) : assert.notMatch(actuals.speech, regex)
      );
    }
    if (paramPassed(regexReprompt)) {
      it(`Alexa's ${type} reprompt should ${not(shouldOrNot)}match: ${regexReprompt}`, () =>

How to use chai.isAtMost:

223
224
225
226
227
228
229
230
231
232
  stack.push(RED.node.message().payload.content);
}
var stats = _.countBy(stack);

assert.isAtLeast(stats['Message 1'], 290);
assert.isAtMost(stats['Message 1'], 380);
assert.isAtLeast(stats['Message 2'], 290);
assert.isAtMost(stats['Message 2'], 380);
assert.isAtLeast(stats['Message 3'], 290);
assert.isAtMost(stats['Message 3'], 380);

How to use chai.isAtLeast:

224
225
226
227
228
229
230
231
232
233
  }
  var stats = _.countBy(stack);

  assert.isAtLeast(stats['Message 1'], 290);
  assert.isAtMost(stats['Message 1'], 380);
  assert.isAtLeast(stats['Message 2'], 290);
  assert.isAtMost(stats['Message 2'], 380);
  assert.isAtLeast(stats['Message 3'], 290);
  assert.isAtMost(stats['Message 3'], 380);
});*/

How to use chai.AssertionError:

214
215
216
217
218
219
220
221
222
223
224
225
}


// Inspired by what is done within chai project itself to test assertions
// https://github.com/chaijs/chai/blob/main/test/bootstrap/index.js
global.chaiErr = function globalErr(fn, val) {
  if (chai.util.type(fn) !== 'function') throw new chai.AssertionError('Invalid fn');


  try {
    fn();
  } catch (err) {

How to use chai.Assertion:

72
73
74
75
76
77
78
79
80
81
const chaiAssertionsCount = require('chai-assertions-count');
chai.use(chaiAssertionsCount);

describe('suite #2', () => {
  beforeEach(() => {
    chai.Assertion.resetAssertsCheck();
  });
  afterEach(() => {
    // you don't need both of them
    chai.Assertion.checkAssertionsCount();

How to use chai.request:

16
17
18
19
20
21
22
23
24
25
it('Verificando se um usuário é registrado com sucesso', async () => {
    sinon.stub(User, 'create').resolves(mockRegister)
    sinon.stub(jwt, 'sign').onFirstCall().returns(mockToken);
    sinon.stub(User, 'findOne').onFirstCall().resolves(undefined).onSecondCall(undefined);

    let chaiHttpResponse = await chai.request(app).post('/register').send({
        name: "Scooby Doo",
        email: "scoobydoo@gmail.com",
        password: "senhaforte123",
        role: "customer"

How to use chai.equal:

82
83
84
85
86
87
88
89
90
91
      shouldOrNot ? assert.equal(actuals.speech, expected) : assert.notEqual(actuals.speech, expected)
    );
  }
  if (paramPassed(expectedReprompt)) {
    it(`Alexa's ${type} reprompt should ${not(shouldOrNot)}equal: ${expectedReprompt}`, () =>
      shouldOrNot ? assert.equal(actuals.reprompt, expectedReprompt) : assert.notEqual(actuals.reprompt, expectedReprompt)
    );
  }
});
return api(); // response.shouldEqual(...).shouldContain(...).{something}

How to use chai.assert:

92
93
94
95
96
97
98
99
100
  
hosts.forEach((host) => {
  assert.isObject(host, `\x1b[31m[CONFIG ERROR] \x1b[0m Each item in the \x1b[33mhosts\x1b[0m array should be an object.`)
  
  const { address, isRFSupported, mac } = host;
  assert(address, `\x1b[31m[CONFIG ERROR] \x1b[0m Each object in the \x1b[33mhosts\x1b[0m option should contain a value for \x1b[33maddress\x1b[0m (e.g. "192.168.1.23").`)
  assert(mac, `\x1b[31m[CONFIG ERROR] \x1b[0m Each object in the \x1b[33mhosts\x1b[0m option should contain a unique value for \x1b[33mmac\x1b[0m (e.g. "34:ea:34:e7:d7:28").`)

  const deviceType = isRFSupported ? 0x279d : 0x2712;

How to use chai.expect:

3
4
5
6
7
8
9
10
11
12

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

chai.use(chaiAsPromised);
var expect = chai.expect;

describe('admin - members', function() {
    before(async function(){
        browser.get(browser.params.glob.host + 'project/project-0/admin/memberships');