Sinon: stub readonly property throw "Cannot stub non-existent property"

Created on 5 Jun 2020  ·  3Comments  ·  Source: sinonjs/sinon

Describe the bug

  • Library version: 9.0.2

To Reproduce

import * as sinon from "sinon";
class B {
    public readonly a: string;
    public get(): void {}
}

const bStub = sinon.createStubInstance(B);
sinon.stub(bStub , "a").value("test");

// let b = new B();
// sinon.stub(b, "a").value("test");

Expected behavior
stub properly.

There is an old issue mentioning the same issue but is closed with a comment that is not quite helpful for me. https://github.com/sinonjs/sinon/issues/829

All 3 comments

However, assigning value beforehand to the property, then the stub will work. But I really don't want to invoke the constructor as it's prettty complicated.

import * as sinon from "sinon";

class B {
    public readonly a: string;
    public get(): void {}
    constructor(aa: string) {
        this.a = aa;
    }
}

// const bStub = sinon.createStubInstance(B);
let b = new B("t");
sinon.stub(b, "a").value("test");
console.log(b.a);

output: test

Currently working around with directly assigning to the stub object.

import * as sinon from "sinon";

class B {
    public readonly a: string;
    public get(): void {}
    constructor(aa: string) {
        this.a = aa;
    }
}

const bStub = sinon.createStubInstance(B);
(bStub as any).a = "test";
console.log(b.a);

output: test

We have made conscious decision to not allow stubbing non-existent properties, as that would make for some very confusing scenarios.

The submitted code doesn't look like JavaScript to me, I don't know how to run it.

Please create a new issue and fill in the template to save everyone some time.

Was this page helpful?
0 / 5 - 0 ratings