Deep Test Diff Test in Karma with Mocha

I run the following test:

describe("objects", function () { it("should equal", function () { var a = { a: 1, b: 2, c: { a: 1, b: 2, c: { a: 1, b: 2, x: 3 } } }; var b = { a: 1, b: 2, c: { a: 1, b: 2, c: { a: 1, b: 2, x: 4 } } }; a.should.deep.equal(b); }); }); 

Testing fails, but the error message does not help at all.

AssertionError: expected { Object (a, b, ...) } to deeply equal { Object (a, b, ...) }

How can I get it so that it outputs a pre-configured json comparison?

The libraries I am currently using:

  • karma 0.12.1
  • karma-mocha 0.1.6
  • karma-mocha-reporter 0.3.0
  • karma-chai 0.1.0
+6
source share
3 answers

You can change where the message is truncated with the following:

chai.config.truncateThreshold = 0

So for your example:

 var chai = require('chai'); var expect = chai.expect; chai.config.truncateThreshold = 0; describe.only("objects", function () { it("should equal", function () { var a = { a: 1, b: 2, c: { a: 1, b: 2, c: { a: 1, b: 2, x: 3 } } }; var b = { a: 1, b: 2, c: { a: 1, b: 2, c: { a: 1, b: 2, x: 4 } } }; expect(a).to.deep.equal(b); }); }); 

This will lead to:

 AssertionError: expected { a: 1, b: 2, c: { a: 1, b: 2, c: { a: 1, b: 2, x: 3 } } } to deeply equal { a: 1, b: 2, c: { a: 1, b: 2, c: { a: 1, b: 2, x: 4 } } } + expected - actual "b": 2 "c": { "a": 1 "b": 2 + "x": 4 - "x": 3 } } } 
+4
source

The mocha reporter has an option for this: showDiff: true

You can insert this into your karma configuration:

 config.set({ frameworks: [ 'mocha', 'chai', ... ], plugins: [ require('karma-mocha'), require('karma-chai'), require('karma-mocha-reporter'), ... ], reporters: [ 'mocha', ... ], mochaReporter: { showDiff: true, // <-- This! }, ... }); 
+1
source

You can use the assert-diff library to show only the difference when the test fails.

 var assert = require('assert-diff'); describe("objects", function () { it("should equal", function () { var a = { a: 1, b: 2, c: { a: 1, b: 2, c: { a: 1, b: 2, x: 3 } } }; var b = { a: 1, b: 2, c: { a: 1, b: 2, c: { a: 1, b: 2, x: 4 } } }; assert.deepEqual(a, b); }); }); 

this will give you an error with a difference

  1) objects should equal: AssertionError: { a: 1, b: 2, c: { a: 1, b: 2, c: { a: 1, b: 2, x: 3 } } } deepEqual { a: 1, b: 2, c: { a: 1, b: 2, c: { a: 1, b: 2, x: 4 } } } { c: { c: { - x: 4 + x: 3 } } } 
0
source

Source: https://habr.com/ru/post/974189/


All Articles