我想对服务文件进行单元测试。
在服务中我有两个功能,getInlineView
和breakByRanges
。
INPUT
const data = {
"text": "Do you have questions or comments and do you wish to contact ABC? Please visit our customer support page.",
"inlineStyleRanges": [],
"inlineEntityRanges": [{
"type": "LINK",
"offset": 83,
"length": 16,
"data": {
"target": "_self",
"url": "/index.htm"
}
}]
}
所以如果我把上面的INPUT
传递给breakData, I get the below
OUTPUT`
OUTPUT
[{"data":"Do you have questions or comments and do you wish to contact ABC? Please visit our ","type":"text"},{"data":"customer support ","type":"LINK"},{"data":"page.","type":"text"}]
以下是我的规格,
describe('GenerateInlineTagsService', () => {
let service: GenerateInlineTagsService;
beforeEach(() => TestBed.configureTestingModule({}));
it('should call getInlineView method ', () => {
const spy = spyOn<any>(service, 'getInlineView').and.returnValue(ENTITY_RANGERS);
service.getInlineView(data);
const obj2 = JSON.stringify(ENTITY_RANGERS); // refers to output mock
expect(JSON.stringify(spy)).toEqual(obj2);
});
});
那么问题呢?
我将data
作为输入传递给getInlineView
,并期望返回值等于模拟值ENTITY_RANGERS
(OUTPUT)。
但我得到以下错误
预期未定义为等于'[{“data”:“您有疑问或意见,是否希望联系ABC?请访问我们的”,“输入”:“text”},{“data”:“客户支持”, “类型”: “LINK”},{ “数据”: “页”, “类型”: “文本”}]”。
请帮忙。
以下是实际功能的链接,
您试图将您在服务功能上设置的间谍与实际预期结果进行比较,这显然不起作用。
将您的代码更改为以下内容:
it('should call getInlineView method ', () => {
const spy = spyOn(service, 'getInlineView').and.returnValue(ENTITY_RANGERS);
expect(spy).not.toHaveBeenCalled();
// this will get you the mock value you provided in your spy above, as all calls to this function will now be handled by the spy
const result = service.getInlineView(data);
expect(spy).toHaveBeenCalledTimes(1);
const obj2 = JSON.stringify(ENTITY_RANGERS); // refers to output mock
expect(JSON.stringify(result)).toEqual(obj2);
});