我需要测试我的功能,但我有困难。
我无法完成100%的覆盖,我的困难与通过函数history.pushState调用的函数onPopState有关。
有人能帮我吗?
// This line is never being covered by my tests
this.locationStrategy.onPopState(() => {
history.pushState(null, null, url);
});我的服务代码:
export class MyService {
constructor(private readonly locationStrategy: LocationStrategy) { }
blockNavigator(url: string) {
history.pushState(null, null, urlAtual);
// This line is never being covered by my tests
this.locationStrategy.onPopState(() => {
history.pushState(null, null, url);
});
}
}我的服务测试代码:
describe('MyService ', () => {
let myService: MyService;
let locationStrategyMock: LocationStrategy;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
BloqueioNavegacaoService,
{
provide: LocationStrategy,
useValue: jasmine.createSpyObj('LocationStrategy', ['onPopState'])
}
]
});
myService = getTestBed().inject(MyService);
locationStrategyMock = getTestBed().inject(LocationStrategy);
});
describe('Methods:', () => {
it('.....', () => {
spyOn(myService , 'blockNavigator').and.callThrough();
locationStrategyMock.onPopState = jasmine.createSpy()
.and.callFake(() => {
// window.history.pushState(null, null, 'url');
});
myService.blockNavigator(url);
expect(myService.blockNavigator).toHaveBeenCalledTimes(1);
expect(window.history.state).toBeNull();
expect(window.history.length).toBeGreaterThanOrEqual(0);
});
});发布于 2021-05-27 12:48:44
我认为您可以利用.calls.mostRecent().args[0]获得函数参数的句柄,并显式调用该函数,然后断言。
请看下面,也有评论。
describe('MyService ', () => {
let myService: MyService;
let locationStrategyMock: LocationStrategy;
// Add this line
let mockLocationStrategy: jasmine.SpyObj<LocationStrategy>;
beforeEach(() => {
// Add this line
mockLocationStrategy = jasmine.createSpyObj('LocationStrategy', ['onPopState']);
TestBed.configureTestingModule({
providers: [
BloqueioNavegacaoService,
{
provide: LocationStrategy,
// change useValue here
useValue: mockLocationStrategy
}
]
});
myService = getTestBed().inject(MyService);
locationStrategyMock = getTestBed().inject(LocationStrategy);
});
describe('Methods:', () => {
it('.....', () => {
// This line is not needed, we call it explicitly
// spyOn(myService , 'blockNavigator').and.callThrough();
myService.blockNavigator(url);
// This line is not needed, we call it explicitly (asserting nothing)
// expect(myService.blockNavigator).toHaveBeenCalledTimes(1);
// get a handle of the function (first argument) of onPopState
// when it is called (i.e. () => {
// history.pushState(null, null, url);
// }
const callBackFunction = mockLocationStrategy.onPopState.calls.mostRecent().args[0];
// Call the function
callBackFunction();
// Hopefully the bottom assertions work
expect(window.history.state).toBeNull();
expect(window.history.length).toBeGreaterThanOrEqual(0);
});
});https://stackoverflow.com/questions/67721936
复制相似问题