假设这样的服务:
@Injectable()
export class PageNavService {
private _expanded = true;
private pageNavExpanded = new Subject<any>();
public togglePageNav(): void {
this._expanded = !this._expanded
this.pageNavExpanded.next(this._expanded);
}
public setPageNavState(expanded) {
this._expanded = expanded;
this.pageNavExpanded.next(this._expanded);
}
public getPageNavState(): Observable<any> {
return this.pageNavExpanded.asObservable();
}
constructor() { }
}
如何测试togglePageNav()
方法?
这是我的尝试:
describe('PageNavService', () => {
let service;
let state;
beforeEach(() => TestBed.configureTestingModule({
providers: [PageNavService]
}));
beforeEach(inject([PageNavService], svc => {
service = svc;
service.getPageNavState().subscribe((s) => {
state = s;
});
}));
describe('togglePageNav method', () => {
it('should reverse the navbar state', () => {
service.togglePageNav();
expect(state).toBeTruthy();
});
});
});
然而,测试失败了:
预计虚假是真的。
答案 0 :(得分:1)
您应该调用方法 $query = new WP_Query( array('post_type' => 'post',
'posts_per_page' =>2,
'order' => 'DESC',
'tax_query' => array(
'taxonomy' => 'NAME OF YOUR CATEGORY',
'field' => 'slug',
'terms' => 'category',
),
)));
,
getPageNavState()
答案 1 :(得分:1)
因为你的初始状态是true
,所以测试不能成功,让我解释一下。
describe('PageNavService', () => {
let service;
let state;
beforeEach(() => TestBed.configureTestingModule({
providers: [PageNavService]
}));
beforeEach(inject([PageNavService], svc => {
service = svc;
//At this moment, the state inside the service is true
service.getPageNavState().subscribe((s) => {
state = s;
});
}));
describe('togglePageNav method', () => {
it('should reverse the navbar state', () => {
//Toggle will change the state from its initial state to an opposite one, making it false
service.togglePageNav();
//The test fails because the state is now false.
expect(state).toBeTruthy();
});
});
});
您可以将初始状态(private _expanded
)更改为false
或将测试更改为false
,因为这是您目前应该获得的。