gpt4 book ai didi

javascript - 类型错误 : undefined is not an object when unit testing with jasmine

转载 作者:太空宇宙 更新时间:2023-11-04 15:29:00 30 4
gpt4 key购买 nike

我正在尝试为函数编写单元测试,但遇到错误。我也不确定如何正确测试函数的其他部分。

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 is not an object (evaluating 'response.data.translationMap')

我需要模拟response.data.translations或分配json结构吗? (translationMap: {'email': 'email', 'forgotPassword': '忘记密码?'})

此外,我不确定如何正确测试函数的其他部分,例如 if 语句或返回可观察值。我是单元测试新手。

最佳答案

您的方法dictionaryMap接受2个参数 - 第一个是loggedIn(大概是 bool 值),第二个是response。在该方法的第一行(在调用 configureMomentLocale 之前),您有一行 const Translations = this.convertToArrays(response.data.translations); ,它需要 response 变量具有名为 data 的属性。

在您的测试中,service.dictionaryMap({}, false); 行中有 2 个错误::

  1. 您正在以相反的顺序设置参数 - 您应该首先放置 bool 参数,然后放置对象
  2. 该对象没有名为 data 的属性

该行应更正为类似于 service.dictionaryMap(false, { data: {} }); 的内容。您甚至可能需要为 data 对象定义 translations 属性 - 这实际上取决于 this.convertToArrays 函数的作用以及它如何处理 未定义的值。

关于javascript - 类型错误 : undefined is not an object when unit testing with jasmine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44959901/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com