angular - 错误: : 找不到对象来监视 Foo()
问题描述
我试图在我的 LoyaltyService 中创建一个简单的 Foo 方法。
public Foo(): Observable<string> {
return of('1');
}
像这样在spec.ts中注入它 -
//const loyaltyService: LoyaltyService = TestBed.inject(LoyaltyService);
const loyaltyService: LoyaltyService = fixture.debugElement.injector.get(LoyaltyService);
spyOn(loyaltyService, 'test').and.returnValue(of('1'));
但是出现错误:错误::找不到用于监视 Foo() 的对象。我已经尝试过 TestBed.inject 方法和 injector.get 方法。
解决方案
AngularJS
当我们在和stub promises
使用中编写测试时,SpyOn
我们做了这样的事情:
spyOn(someService,'get').and.returnValue(deferred.promise);
上面的代码是完全有效的——不像observables
,promises
总是异步的。但是如何测试Observables
?使用jasmine-marbles
是这里最好的部分。所以尝试这样的事情:
app-foo.component.ts
@Component({
selector: 'app-foo',
template: `
<div class="foo">
{{ foo | async }}
</div>
`
})
export class FooComponent implements OnInit {
foo: string = "";
constructor(private fooService: FooService) { }
ngOnInit() {
this.fooService.get().subscribe(res => {
this.foo = res;
});
}
}
app-foo.component.spec.ts
import { cold, getTestScheduler } from 'jasmine-marbles';
const fooServiceStub = {
get() {
const foo$ = cold('--x|', { x: `1` });
return foo$
}
};
describe('FooComponent', () => {
it('should work', () => {
const foo = element.querySelectorAll('.foo');
getTestScheduler().flush(); // flush the observables
fixture.detectChanges();
expect(element.querySelectorAll('.foo').length).toEqual(1);
});
});
有关observables
测试的更多信息,请参阅以下文章:
推荐阅读
- bash - wget 命令用于在 allocine 上请求身份验证后下载视频
- javascript - 在 div 内拖动元素
- sql - How to move all non-null values to the top of my column?
- progressive-web-apps - Lighthouse (PWA) 为 Bootstrap CSS 显示“消除渲染阻塞资源”,但我使用的是“异步”
- php - 如何在wordpress中选择哪些帖子进入哪个页面模板?
- reactjs - Change path in asset-manifest.json
- r - how to unlist a list of regression models in R
- mongodb - 使用 AWS Amplify 和 App Sync 与使用 Mongodb 的现有节点服务器
- mysql - MySQL选择可能的正则表达式问题
- ios - ld: symbol(s) not found for architecture arm64 TwiterKit