【问题标题】:Stubbing ES6 prototype methods using sinon使用 sinon 存根 ES6 原型方法
【发布时间】:2017-04-27 07:25:12
【问题描述】:

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

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

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

我在 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 的子类

"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 为此创建一个测试用例

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();
});
});

【问题讨论】:

    标签: javascript ecmascript-6 mocha.js tdd sinon


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢 :) ,另一个疑问,知道为什么 this.Role 的值在这一行中出现为 undefined routesLogger.logError(this.Role, "GetMyDetails", err);在 student.js 类中?
    • 因为this 不引用类实例。应该使用箭头(err, result) => { 而不是function (err, result) {。顺便说一句,this.Role = role; 在子类中是多余的,它已经通过调用 super(...) 来完成。
    • 构造函数呢?有什么办法可以模拟它吗?
    • @kord 存根构造函数对 JS 类没有意义,因为类构造函数本身就是一个类。您可能需要模拟一个从中导入类的模块并存根一个类。
    猜你喜欢
    • 2016-11-08
    • 2016-09-25
    • 2016-09-21
    • 2015-04-18
    • 2021-06-10
    • 1970-01-01
    • 2014-07-17
    • 2014-08-08
    • 2017-07-09
    相关资源
    最近更新 更多