【问题标题】:Angular unit test - changing a mock service class's method return for individual testsAngular 单元测试 - 更改单个测试的模拟服务类的方法返回
【发布时间】:2021-07-01 13:34:50
【问题描述】:

在我的单元测试中,我有一个正在使用的模拟服务类MockWorkflowService,它有一个方法getActiveTask。大部分测试都需要此方法的默认功能,但是有几个测试我需要重写此方法并让它返回 null。但是我这样做没有任何运气(请参阅代码块底部的测试):

class MockWorkflowService {
  getActiveTask() {
    return new Action({
      name: 'test',
      value: 4
    })
  }
}

describe('MyComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        MyComponent
      ],
      providers: [
        TranslateService,
        { provide: WorkflowService, useClass: MockWorkflowService }
      ]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should ...', () => {
    // TRYING TO DO SOMETHING LIKE
    MockWorkflowService.getActiveTask = () => null;
  });

})

我尝试执行 MockWorkflowService.prototype.getActiveTask = () => null,它适用于我想要覆盖它的单个测试,但随后该方法对所有剩余测试返回 null。

任何帮助将不胜感激,谢谢。

【问题讨论】:

    标签: angular unit-testing jasmine


    【解决方案1】:

    当您只想为该特定测试覆盖时,您需要执行此操作。您正在做的是覆盖该服务的所有实例,这是错误的。你可以按照这个:

    // Define the service here: 
    describe('MyComponent', () => {
      let workflowService: WorkFlowService // Add this line
      beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [
            MyComponent
          ],
          providers: [
            TranslateService,
            { provide: WorkflowService, useClass: MockWorkflowService }
          ]
        })
          .compileComponents();
      }));
    
    // In before each, create an instance of the service
     beforeEach(() => {
        fixture = TestBed.createComponent(MyComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
        workFlowService = TestBed.get(WorkflowService); // Add this line
        // TestBed.get should be TestBed.inject if you're using Angular 9+
      });
    
    
    it('should ...', () => {
      // Spy on the service and return null
      // This will call the mock service class and return null for this test case
    
      spyOn(workFlowService, 'getActiveTask').and.returnValue(null);
      component.yourComponentMethodName();
      expect(component.yourComponentMethodName).toHaveBeenCalled();
    });
    

    【讨论】:

    • 这个答案很好,但我做了一些修改。
    • 非常感谢你们两位,这一切都很有意义,并且对我来说非常有用!!非常感谢您的帮助,我无法弄清楚。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    • 1970-01-01
    • 2020-03-17
    • 1970-01-01
    相关资源
    最近更新 更多