Javascript TypeError:使用jasmine进行单元测试时,undefined不是对象
我试图为一个函数编写一个单元测试,但我得到了一个错误。我也不确定如何正确测试函数的其他部分Javascript TypeError:使用jasmine进行单元测试时,undefined不是对象,javascript,unit-testing,jasmine,Javascript,Unit Testing,Jasmine,我试图为一个函数编写一个单元测试,但我得到了一个错误。我也不确定如何正确测试函数的其他部分 private dictionaryMap (loggedIn, response) { const translations = this.convertToArrays(response.data.translations); this.configureMomentLocale(language); if (!loggedIn) { this.cacheP
private dictionaryMap (loggedIn, response) {
const translations = this.convertToArrays(response.data.translations);
this.configureMomentLocale(language);
if (!loggedIn) {
this.cachePublicDictionary(translations);
}
// not testing this part
this.dictionary = new Dictionary({
translationMap: Object.assign({}, this.getPublicDictionaryFromCache() || {}, translations),
});
return this.rx.Observable.of(this.dictionary);
}
到目前为止,我的单元测试如下所示:
describe('dictionaryMap', () => {
it('calls configureMomentLocale()', () => {
const foo = {
'foo':'bar',
};
spyOn(service, 'configureMomentLocale');
service.dictionaryMap({}, false);
expect(service.configureMomentLocale).toHaveBeenCalled();
});
});
当我运行此测试时,我得到以下错误:
TypeError:undefined不是对象(正在计算'response.data.translationMap')
我需要模拟response.data.translations还是分配json结构?(translationMap:{'email':'email','forgotPassword':'忘记密码?})
另外,我不知道如何正确测试函数的其他部分,比如if语句或返回可观察的对象。我不熟悉单元测试。您的方法
字典map
接受两个参数-第一个参数是loggedIn
(可能是布尔值),第二个参数是response
。在该方法的第一行(在调用configureMomentLocale
之前),您有一行const translations=this.convertToArrays(response.data.translations)
它期望响应
变量具有名为数据
的属性
在测试中,service.dictionaryMap({},false)一行有2个错误代码>:
您正在按相反的顺序设置参数-您应该将布尔参数放在第一位,将对象放在第二位
对象没有名为data
应该将该行更正为类似于service.dictionaryMap(false,{data:{}})代码>。您甚至可能需要为数据
对象定义翻译
属性-这实际上取决于这个函数的功能以及它如何处理未定义的值。我觉得很愚蠢!真不敢相信我搞错了。答案非常翔实,我从中学到了很多。非常感谢。