单元测试一种返回预期值的方法



我想单元测试服务文件。

在服务中,我有两个功能, getInlineView&breakByRanges

输入

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输出

输出

[{"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(输出)。

但是我得到以下错误

期望不确定的不相等'[{" data":"您有问题还是 评论,您想与ABC联系吗?请访问我们的 ","类型":"文本"},{" data":"客户支持 ","类型":" link"},{" data":" page。"," type":" text"}]'。

请帮助。

以下是实际功能的链接

https://stackblitz.com/edit/typescript-qxndgd

您正在尝试将您在服务功能上设置的间谍与实际预期结果进行比较,这显然不起作用。

将您的代码更改为:

的线
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);
});

最新更新