Shamshiel
Shamshiel

Reputation: 2211

Sinon stub throws "TypeError: Cannot redefine property"

I'm using the NPM package Jose (version v1.28.0) in one of my NodeJS applications. Recently my renovate bot tried to update it to the next major version 2.0.2. Sadly my unit tests with Sinon don't work anymore with this version. My application itself works without any problems...

I'm getting the following error:

TypeError: Cannot redefine property: decode
    at Function.defineProperty (<anonymous>)

This is the code that triggers the error:

 import { JWT, JWK } from 'jose';
 // other code ...
 sandbox.stub(JWT, 'decode').returns(decodedResult);

I'm at a loss at what I need to change in the unit test to get it working again. If the 'decode' method is not stubbed it will always throw an error with my fake input values.

Upvotes: 3

Views: 3755

Answers (3)

Jacob Bralish
Jacob Bralish

Reputation: 271

I was able to mock the decode method on the jwtwebtoken library like so:

    import jsonwebtoken from "jsonwebtoken";

    const spy = sinon.fake.returns(value);

    sinon.replace(jsonwebtoken, "decode", spy);

Where value is the return value you would expect.

Upvotes: 0

user9775882
user9775882

Reputation:

sinon works by re-defining properties, the property has been made intentionally non-enumerable but in the process also not configurable. This is soon to be fixed in v2.0.3

Upvotes: 2

York Chen
York Chen

Reputation: 742

If you look into the document of JWT object, it doesn't has a "decode" function, so you cannot stub it.

https://github.com/panva/jose/blob/master/docs/README.md#jwt-json-web-token

Upvotes: 0

Related Questions