使用 sinon 存根 ES6 原型方法 [英] Stubbing ES6 prototype methods using sinon

查看:63
本文介绍了使用 sinon 存根 ES6 原型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Sinon 存根超类的原型方法时遇到问题.在下面的示例中,我将调用超类方法 GetMyDetails,如下所示.我相信有更好的方法.

I am having a problem stubbing the prototype methods of the super class using Sinon. In the example below I am stubbing the call to super class method GetMyDetails as follows. I am sure there is a better way.

actor = sinon.stub(student.__proto__.__proto__,"GetMyDetails");

而且 this.Role 的值也最终未定义.

And also the value of this.Role ends up being undefined.

我在 javascript 中创建了一个简单的类

I have created a simple class in javascript

"use strict";
class Actor {
constructor(userName, role) {
    this.UserName = userName;
    this.Role = role;
}

GetMyDetails(query,projection,populate,callback) {
    let dal = dalFactory.createDAL(this.Role);
    dal.PromiseFindOneWithProjectionAndPopulate(query, projection, populate).then(function (data) {
        callback(null,data);
    }).catch(function (error) {
        routesLogger.logError(this.Role, "GetMyDetails", error);
        return callback(error);
    })

}
}
 module.exports = Actor;

现在我有一个扩展 Actor.js 的子类

Now I have a child class that extends Actor.js

"use strict";
 class student extends Actor{
constructor(username, role) {
    super(username, role);
    this.UserName = username;       
    this.Role = role;
}

GetMyDetails(callback) {
    let query = {'username': this.UserName};
    let projection = {};
    let populateQuery = {}

    super.GetMyDetails(query, projection, populateQuery, function (err, result) {
        if (err) {
            routesLogger.logError(this.Role, "GetMyDetails", err);
            callback(err, null);
        }
        else
            callback(null, result);
    });
}

}

我尝试使用 mocha 为此创建一个测试用例

I have tried to create a test case for this using mocha

describe("Test Suite For Getting My Details",function(){

let request;
let response;
let actor;


beforeEach(function () {
    request = {
        session: {
            user: {
                email: 'student@student.com',
                role: 'student'
            }
        },
        originalUrl:'/apssdc'
    };
    response = httpMocks.createResponse();

});

afterEach(function () {

});



it("Should get details of the student",function(done){
    let username = "student";
    let role = "Student";
    let student = new Student(username,role);
    actor = sinon.stub(student.__proto__.__proto__,"GetMyDetails");
    actor.yields(new Error(), null);

    sc.GetMyDetails(function(err,data){
        console.log(data);
        console.log(err);
    });
    done();
});
});

推荐答案

原型方法应该直接在原型上存根/窥探:

Prototype methods should be stubbed/spied directly on the prototype:

sinon.stub(Actor.prototype,"GetMyDetails");

这篇关于使用 sinon 存根 ES6 原型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆