【问题标题】:Unit test a method to return the expected value单元测试返回期望值的方法
【发布时间】:2019-03-12 20:19:18
【问题描述】:

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

在服务中我有两个函数,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 belowOUTPUT`

输出

[{"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":"您有问题或 cmets,您想联系 ABC 吗?请访问我们的 ","type":"text"},{"data":"客户支持 ","type":"LINK"},{"data":"page.","type":"text"}]'。

请帮忙。

下面是实际功能的链接,

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

【问题讨论】:

    标签: angular jasmine karma-jasmine


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-08
      • 1970-01-01
      • 2014-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多