Jasmine 验证订阅中行为主体的可观察值

Jasmine 验证订阅中行为主体的可观察值,jasmine,angular-test,Jasmine,Angular Test,我有一个简单的服务,它查询web,然后根据返回结果,通过BehaviorSubject 导出类产品服务{ 静态只读baseUrl=`${environment.apiUri}/producers` private readonly admin=new BehaviorSubject(false) 只读管理员$=this.admin.asObservable() 构造函数(专用只读http:HttpClient){ } queryAdmin():void{ this.http.get(`${Pro

我有一个简单的服务,它查询web,然后根据返回结果,通过
BehaviorSubject

导出类产品服务{
静态只读baseUrl=`${environment.apiUri}/producers`
private readonly admin=new BehaviorSubject(false)
只读管理员$=this.admin.asObservable()
构造函数(专用只读http:HttpClient){
}
queryAdmin():void{
this.http.get(`${ProducerService.baseUrl}/admin`)
.subscribe(x=>this.admin.next(x))
}
}
现在我试图编写一个测试,验证
admin$
变量是否设置为true时是否传递了true。我是这样试的

it('当管理员时应发出true',异步(()=>{
service.admin$.subscribe(x=>expect(x.toBeTrue())
service.queryAdmin()
const req=httpMock.expectOne({url:`${ProducerService.baseUrl}/admin`,方法:'GET'})
请求刷新(真)
}))
尽管说“预期虚假为真实”,但这一点还是失败了。我做错了什么?

BehaviorSubject是“热”的,所以当您订阅它时,它就可以启动了,并且它的初始值为false,然后您将断言false为etrue

尝试使用Rxjs的filter操作符过滤掉假值

import { filter } from 'rxjs/operators';
....
it('should emit true when an admin', async((done) => {
    service.admin$.pipe(
      filter(admin => !!admin), // the value of admin has to be true for it to go into the subscribe block
    ).subscribe(x => { 
      expect(x).toBeTrue(); 
      done(); // add the done function as an argument and call it to ensure
    });       // test execution made it into this subscribe and thus the assertion was made
              // Calling done, tells Jasmine we are done with our test.

    service.queryAdmin()
    const req = httpMock.expectOne({url: `${ProducerService.baseUrl}/admin`, method: 'GET'})
    req.flush(true)
}))

我必须在这里做很多事情。无法使用async或它不喜欢done方法。必须按照@AliF50建议的方式进行筛选,我必须传入一个值1而不是true。因此,我在测试中得出以下结论:

it('当管理员时应发出true',(完成)=>{
服务管理员$
.管道(过滤器(x=>x))
.订阅(x=>{
expect(x).toBeTrue()
完成()
})
service.queryAdmin()
const req=httpMock.expectOne({url:`${ProducerService.baseUrl}/admin`,方法:'GET'})
要求冲洗(1)
})
这也意味着我必须修改我的
queryAdmin
方法,以便执行
像这样:

queryAdmin():void{
//这是为producer.service.spec.ts文件执行的,因为它
//不会自动解码“true”值,因此我必须传入1
//作为主体(即一个真值),然后这个!!x将其转换为真。
//无检查点的工具表达式JS
this.http.get(`${ProducerService.baseUrl}/admin`)。订阅(x=>this.admin.next(!!x))
}

谢谢,这很有道理。现在它说
失败了:响应类型不支持自动转换为JSON。
看看sloosch或adamlarner的帖子是否对您有所帮助,我想您遇到了这个问题。