Angular单元测试:服务函数返回的值

Angular unit test: value returned by service function

我正在为 angular 应用编写单元测试,我正在测试服务。当我期望服务函数返回的值等于 'king'.

时,测试失败

service.ts

@Injectable()
export class TopToolBarService {

 customer = null;
 getCustomer() {
    return this.customer;
  }
}

test.spec.js

it ('should check return value of service',() = > {
 let service:TopToolBarService
 const valueServiceSpy = jasmine.createSpyObj('TopToolBarService', ['getCustomer']);
 valueServiceSpy.and.returnValue("king");
 var result = component.getCustomer();
 expect (result).toBe("king");
//test failed, value of result is null

})



这需要函数的 return 值,而不是整个对象,试试这个:

it ('should check return value of service', () => {
 let mockTopToolBarService: jasmine.SpyObj<TopToolBarService>;
 mockTopToolBarService = jasmine.createSpyObj('TopToolBarService', ['getCustomer']);
 mockTopToolBarService.getCustomer.and.returnValue("king");

 var result = component.getCustomer();
 expect(result).toBe("king");
});

请注意,service 指向一个带有名为 getCustomer 的间谍的对象 - 我更新了 it 以更好地说明正在发生的事情。

您需要考虑的另一件事是 TopToolBarService 在规范中可能被嘲笑得太晚了。我通常像这样在顶部嘲笑他们:

describe('Component', () => {
  beforeEach(() => {
    let mockTopToolBarService: jasmine.SpyObj<TopToolBarService>;
    mockTopToolBarService = jasmine.createSpyObj('TopToolBarService', ['getCustomer']);
    mockTopToolBarService.getCustomer.and.returnValue("king");

    TestBed.configureTestingModule({
      declarations: [Component],
      providers: [{ provide: TopToolBarService, useValue: mockTopToolBarService}]
    });

    const fixture = TestBed.createComponent(Component);
    component = fixture.componentInstance;

    fixture.detectChanges();
  });


  it ('should check return value of service', () => {
    var result = component.getCustomer();
    expect(result).toBe("king");
  });
});

当您像这样在规范顶部定义模拟服务时,它会被注入到您的规范中,并且会使用您的模拟服务而不是真正的服务。