Ani*_*Das 4 angular angular-unit-test angular-test
我正在对一个 Angular 应用程序进行单元测试,我需要模拟一个服务。我可以毫无问题地模拟服务方法,但是当我尝试以相同的方式模拟属性时,它给了我错误
我的配置服务有一个属性和一种方法,我想模拟该属性,因为我无法生成该值。
服务
@Injectable()
export class ConfigService {
public config = 'iamdirect';
constructor(private http: Http) {
}
public load(): Observable<any> {
return 'Iamokey';
}
}
Run Code Online (Sandbox Code Playgroud)
在角度测试中模拟服务
// mocking config service
configService = TestBed.get(ConfigService);
spyOn(configService, 'load')
.and.returnValue(Observable.of({
contactDetails: {
emailAddress: 'testemail@email.com'
}
}));
Run Code Online (Sandbox Code Playgroud)
当我这样做时,它给了我错误。
spyOn(configService, 'config') //config is the property
.and.returnValue(Observable.of({
contactDetails: {
emailAddress: 'testemail@email.com'
}
}));
Run Code Online (Sandbox Code Playgroud)
您可以使用 jasmine 创建间谍对象,也可以使用模拟对象作为服务存根。
let mockConfigService;
let configService: ConfigService;
const subject = new Subject();
beforeEach(() => {
mockConfigService = {
config: 'test text',
load: () => subject.asObservable()
}
TestBed.configureTestingModule({
providers: [
{provide: ConfigService, useValue: mockConfigService},
]
});
configService = TestBed.get(ConfigService);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5451 次 |
| 最近记录: |