javascript - Kan ikke stubbe pilfunksjon i en klasse ved bruk av Sinon


  • Sinon-versjon: v2.0.0-pre.2
  • Miljø : Windows 10
  • Andre biblioteker du bruker: Typescript, babel, mocha, chai

Hva forventet du skulle skje?

Jeg forventet å kunne stubbe en pilfunksjon i en klasse.

Hva som egentlig skjer

Jeg kan ikke stubbe en pilfunksjon, men jeg kan stubbe klasseprototypefunksjonen.

FAILED TESTS:
  ExampleClass tests
    × should stub thisDoesntWork arrow function
      Chrome 52.0.2743 (Windows 10 0.0.0)
    TypeError: Attempted to wrap undefined property thisDoesntWork as function
        at wrapMethod (webpack:///~/sinon/pkg/sinon.js:3138:0 <- test-bundler.js:7377:21)
        at Object.stub (webpack:///~/sinon/pkg/sinon.js:2472:0 <- test-bundler.js:6711:12)
        at Context.<anonymous> (webpack:///src/stores/sinon.test.ts:22:51 <- test-bundler.js:96197:72)

Hvordan reprodusere

export class ExampleClass {
    thisWorks() {
        return 0;
    }

    thisDoesntWork = () => {
        return 0;
    }
}

describe("ExampleClass tests", () => {
    it("should stub thisWorks function", () => {
        let stubFunctionA = sinon.stub(ExampleClass.prototype, "thisWorks");
    });
    it("should stub thisDoesntWork arrow function", () => {
        let stubFunctionB = sinon.stub(ExampleClass, "thisDoesntWork");
    });
});

Svar #1

Jeg har aldri brukt sinon, men i dokumentasjonen deres står det for sinon.stub-funksjonen at den:

Erstatter object.method med en stub-funksjon

Hvis du ser på den kompilerte js-koden til din ExampleClass:

var ExampleClass = (function () {
    function ExampleClass() {
        this.thisDoesntWork = function () {
            return 0;
        };
    }
    ExampleClass.prototype.thisWorks = function () {
        return 0;
    };
    return ExampleClass;
}());

Da vil du se at ExampleClass.prototype.thisWorks er definert, men det finnes ingen ExampleClass.thisDoesntWork-definisjon, ikke engang ExampleClass.prototype.thisDoesntWork.

Metoden thisDoesntWork legges til kun i konstruktøren (pilfunksjoner er egentlig ikke klassemetoder, de er bare klassemedlemmer med funksjonstype).

Jeg mistenker at dette vil fungere:

describe("ExampleClass tests", () => {
    it("should stub thisDoesntWork arrow function", () => {
        let stubFunctionB = sinon.stub(new ExampleClass(), "thisDoesntWork");
    });
});

Relaterte artikler