简体   繁体   中英

jsMockito: How to run callback sended to mock?

I am learning how to use jsMockito to write perfect code. So, could you give me any idea on how to run callback which is provided to service?

Here is my class:

function MyClass(service) {
    this.service = service;
}

MyClass.prototype.doSomething = function() {
    this.service.doIt(function() {
        console.log("How to run this function while running tests?");
    })
}

And here is my test:

var MyClassTest = TestCase("MyClassTest");

MyClassTest.prototype.testMyClass = function() {
    this.service = mock(Service);
    this.myClass = new MyClass(this.service);
    this.myClass.doSomething();
}

So, I need to see the log message: "How to run this function while running tests?"

Any ideas are welcome.

Finally I have found the solution.

We need to create doItCallback :

function MyClass(service) {
    this.service = service;
}

MyClass.prototype.doItCallback = function() {
    console.log("How to run this function while running tests?");
}

MyClass.prototype.doSomething = function() {
    this.service.doIt(this.doItCallback);
}

Also we need to update the mock:

var MyClassTest = TestCase("MyClassTest");

MyClassTest.prototype.testMyClass = function() {
    this.service = mock(Service);
    this.myClass = new MyClass(this.service);
    var myClass = this.myClass;
    when(this.service).doIt().then(function() {
        myClass.doItCallback();
    });
    this.myClass.doSomething();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM