我正在使用Jasmine进行一些单元测试。我有一个模块getContacts
,使用module.exports
和require
成功注入到规范中。虽然我可以访问模块本身,但模块方法返回undefined,所以我无法将它们作为单元进行测试。以下是该模块的代码:
var getContacts = function() {
var GetContacts = this;
var contacts = require('nativescript-contacts');
var model = require("../main-view-model");
GetContacts.init = (function() {
var self = this;
contacts.getContact().then(function(args){
self.makeName(args.data);
self.getPhoneNumber(args.data);
}).catch(function(e) {
console.log("promise \"contacts.getContact()\" failed with" + e.stack + "\n" + "value of self:" + " " + self)
});
}());
GetContacts.getPhoneNumber = function(data) {
if(data.phoneNumbers.length > 0){
model.phone = data.phoneNumbers[0];
}
};
GetContacts.makeName = function(data) {
if(data.name.displayname) {
model.contactName = data.name.displayname;
}
else {
}
model.contactName = data.name.given + " " + data.name.family;
};
};
module.exports = getContacts;
和spec文件:
describe("getContacts", function() {
"use strict";
var contacts, model, getContacts, data;
beforeEach(function() {
contacts = require('nativescript-contacts');
model = require("../main-view-model");
getContacts = require('../src/getContacts.js');
data = {
"data": {
"name": {
"given": "John",
"middle": "Peter",
"family": "Smith",
"prefix": "Mr.",
"suffix": "Jr.",
"testEmptyObject": {},
"testEmptyString": "",
"testNumber": 0,
"testNull": null,
"testBool": true,
"displayname": "John Smith",
"phonetic": {
"given": null,
"middle": null,
"family": null
}
}
},
"response": "selected"
}
});
it("Gets the display name as contact name if display name is a string with length", function() {
expect(getContacts.makeName(data)).toBe("John Smith");
});
});
测试失败并显示错误:
getContacts.makeName
不是函数
确实记录它会返回undefined
。但是,记录getContacts
会将整个getContacts
函数打印到控制台。如何访问makeName
和其他方法,以便我可以在个人层面对它们进行单元测试?
答案 0 :(得分:1)
在没有包装匿名函数的情况下需要重构代码。我认为不需要它,因为模块本身会产生分离。以下是有效的代码:
var contacts = require(' nativescript-contacts'); var model = require(" ../ main-view-model");
var GetContacts = {
init: function() {
var self = this;
contacts.getContact().then(function(args){
model.contactName = self.makeName(args.data);
model.phone = self.getPhoneNumber(args.data);
}).catch(function(e) {
console.log("promise \"contacts.getContact()\" failed with" + e.stack + "\n" + "value of self:" + " " + self)
});
},
getPhoneNumber: function(data) {
if(data.phoneNumbers.length > 0){
return data.phoneNumbers[0];
}
},
makeName: function(data) {
if(data.name.displayname) {
return data.name.displayname;
}
else {
}
}
};
module.exports = GetContacts;
答案 1 :(得分:0)
函数不会返回任何内容,因此函数会执行某些操作但却不知道对其中的代码的进一步引用,因此请尝试在函数末尾添加return,如下所示;)
var getContacts = function() {
var GetContacts = this;
/*
rest of code
*/
GetContacts.makeName = function(data) {
if(data.name.displayname) {
model.contactName = data.name.displayname;
}
else {
}
model.contactName = data.name.given + " " + data.name.family;
};
//add return to export content of function
return GetContacts;
};