在Angular 8中,Jasmine Spy和returnValue有不同的类型。下面是一些示例代码,展示了如何使用这些不同类型:
import { TestBed } from '@angular/core/testing';
import { UserService } from './user.service';
describe('UserService', () => {
let service: UserService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(UserService);
});
it('should create a spy for a method', () => {
const spy = spyOn(service, 'getUser').and.returnValue({ id: 1, name: 'John' });
expect(service.getUser()).toEqual({ id: 1, name: 'John' });
expect(spy).toHaveBeenCalled();
});
});
import { TestBed } from '@angular/core/testing';
import { UserService } from './user.service';
describe('UserService', () => {
let service: UserService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(UserService);
});
it('should create a spy for a method and return a specific value', () => {
const spy = spyOn(service, 'getUserById').and.returnValue(1);
expect(service.getUserById(1)).toEqual(1);
expect(spy).toHaveBeenCalled();
});
});
请注意,在第一个示例中,returnValue
是一个简单的对象字面量,而在第二个示例中,returnValue
是一个具体的值,这取决于被调用的函数的返回类型。
希望这些示例能帮助你理解Angular 8中Jasmine Spy和returnValue的不同类型的使用方法。