Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript TypeError:使用jasmine进行单元测试时,undefined不是对象_Javascript_Unit Testing_Jasmine - Fatal编程技术网

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:{}})。您甚至可能需要为
    数据
    对象定义
    翻译
    属性-这实际上取决于
    这个函数的功能以及它如何处理
    未定义的值。

    我觉得很愚蠢!真不敢相信我搞错了。答案非常翔实,我从中学到了很多。非常感谢。