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

问题描述 投票:1回答:1

我想对服务文件进行单元测试。

在服务中我有两个功能,getInlineViewbreakByRanges

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 belowOUTPUT`

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”},{ “数据”: “页”, “类型”: “文本”}]”。

请帮忙。

以下是实际功能的链接,

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

angular jasmine karma-jasmine
1个回答
0
投票

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

将您的代码更改为以下内容:

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);
});
© www.soinside.com 2019 - 2024. All rights reserved.