chaijs / chai

BDD / TDD assertion framework for node.js and the browser that can be paired with any testing framework.
https://chaijs.github.io
MIT License
8.11k stars 694 forks source link

BigInt are not supported in .deep.equal() #1623

Open SmashingQuasar opened 3 months ago

SmashingQuasar commented 3 months ago

Hey!

I am using the latest version of Chai and it appears if you try to deep equal an object that has a property of type BigInt, Chai will throw an Error.

Here is a code sample that should reproduce the issue (TypeScript):

import { describe, it } from "mocha";
import { expect } from "chai";

class Foo {
  private bar: BigInt = 0n;
}

describe("BigInt are not supported", (): void => {
  it("should work", (): void => {
    const instance: Foo = new Foo();
    const secondInstance: Foo = new Foo();

    expect(instance).to.deep.equal(secondInstance); // This will throw
  });
});

Support for BigInt was apparently added a while back but it seems it no longer works or deep.equal did not work.

SmashingQuasar commented 3 months ago

As a workaround for anyone encountering this issue, you add this to your runner pre-run script:

    // eslint-disable-next-line no-extend-native -- Chai does not support BigInt serialisation.
    Object.defineProperty(
        BigInt.prototype,
        "toJSON",
        {
            writable: false,
            enumerable: false,
            configurable: false,
            value: function(): string
            {
                // eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/restrict-template-expressions
                return `${this.toString()}n`;
            },
        }
    );

It's unclean but at least it works.

43081j commented 2 months ago

i tried the exact code in the first post and it seems to work fine for me

could you give some more info, like how you're building and running this test?

e.g. do you use ts-node or do you run the built JS? do you output commonjs or esm? etc etc

SmashingQuasar commented 2 months ago

i tried the exact code in the first post and it seems to work fine for me

could you give some more info, like how you're building and running this test?

e.g. do you use ts-node or do you run the built JS? do you output commonjs or esm? etc etc

Hey!

Thanks for your answer. To help understand this problem, I will create a repository aiming to replicate the issue with a few dependencies and code as possible and post it here. That way I will either find my own mistake or save you time instead of making you blindly look for the problem.