Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to add custom methods to assert interface of chai?

Is there any way to add custom methods to assert interface of chai?

I've tried with:

// test-helper.js

export const testPlugin = function(chai) {
    chai.Assertion.addMethod('customMethod', function() {
      //Something
    })
 }

// abc.test.js

import {assert, use} from 'chai'
import {testPlugin} from 'test-helper.js'

use(testPlugin)

But I think this only works for the expect interface of chai. I want to use this custom method as assert.customMethod(actual, expected)

Let me know if I am missing something here.

like image 351
Pankaj Pandey Avatar asked Jun 13 '18 13:06

Pankaj Pandey


People also ask

How do you assert chai?

var assert = require('chai'). assert , foo = 'bar' , beverages = { tea: [ 'chai', 'matcha', 'oolong' ] }; assert. typeOf(foo, 'string'); // without optional message assert. typeOf(foo, 'string', 'foo is a string'); // with optional message assert.

Should I assert vs vs expect?

Note expect and should uses chainable language to construct assertions, but they differ in the way an assertion is initially constructed. In the case of should , there are also some caveats and additional tools to overcome the caveats. var expect = require('chai').

Is Chai an assertion library?

Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework.

What assertion styles are present in Chai testing assertion library?

Chai is such an assertion library, which provides certain interfaces to implement assertions for any JavaScript-based framework. Chai's interfaces are broadly classified into two: TDD styles and BDD styles.


1 Answers

Expanding the other answer... look at the definition for Chai's assert.equal and the other native assertions for reference. Your custom assertion might look like:

const chai = require("chai");
chai.assert.assertSpecial = function (actual) {
    // see https://github.com/chaijs/chai/blob/master/lib/chai/assertion.js
    // for Assertion's argument definitions
    const test = new chai.Assertion(null, null, chai.assert, true);
    test.assert(
        actual === "special",
        `expected ${actual} to be "special"`,
        `expected ${actual} to not be "special"`,
        "special",
        actual,
        true);
};
like image 167
ZachB Avatar answered Nov 10 '22 19:11

ZachB