【问题标题】:Angular testing: mock the value of a constant角度测试:模拟常量的值
【发布时间】:2021-02-18 17:12:40
【问题描述】:

我有一个简单的应用程序:

  • AppComponent 从服务中获取要显示的活动列表
  • ActivitiesService 从导入的常量中获取列表
  • 在我的测试文件 activities.service.spec.ts 我想模拟那个常量

为方便起见,我设置了一个 StackBlitz(包括测试)以 'given/when/then' 形式 (link) 和另一个经典的 'beforeEach/it()' 形式 (link) .他们应该做同样的事情,但有些人比另一种更喜欢一种风格......如果这两种风格中的任何一种都在运行,我会很高兴。

在测试中我添加了{ provide: ACTIVITIES, useValue: fakeActivities },因为我相信解决方案必须放在某个地方......但是我该如何应用它呢?显然我不能注入它......

【问题讨论】:

    标签: angular testing karma-jasmine


    【解决方案1】:

    您可以在getActivities() 上使用spyOn 方法,如下所示:

    import { TestBed } from "@angular/core/testing";
    import { ACTIVITIES } from "../data/activities-mock";
    import { Activity } from "../models/activity";
    import { ActivitiesService } from "./activities.service";
    import Spy = jasmine.Spy;
    fdescribe("ActivitiesService", () => {
      let serviceUnderTest: ActivitiesService;
      let actualResult: Activity[];
    
      beforeEach(() => {
        TestBed.configureTestingModule({
          providers: [
            ActivitiesService
          ]
        });
        serviceUnderTest = TestBed.inject(ActivitiesService);
      });
    
      it("should get Activities", () => {
        spyOn(serviceUnderTest, 'getActivities').and.returnValue(fakeActivities);
        actualResult = serviceUnderTest.getActivities();
        expect(actualResult).toEqual(fakeActivities);
      });
    });
    
    const fakeActivities: Activity[] = [
      {
        id: 1,
        name: "stretching"
      },
      {
        id: 2,
        name: "climbing"
      }
    ];
    

    【讨论】:

    • 嗨,OLO,谢谢,但我认为这是在模拟被测函数本身。同时我通过另一个渠道获得了解决方案,我将在今天晚些时候将其发布在这里。不过再次感谢!
    • 实际上,再三考虑,这是一个有效的解决方案。我会接受的。谢谢。
    猜你喜欢
    • 2022-01-10
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    • 2018-12-13
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多