gpt4 book ai didi

unit-testing - Jasmine route spy - undefined 不是对象(评估 'navigate.calls.mostRecent().args' )

转载 作者:搜寻专家 更新时间:2023-10-30 21:52:41 24 4
gpt4 key购买 nike

我正在尝试对使用路由的 angular2 组件进行单元测试。我有:

class MockRouter {
}

class MockAuth {
isLoggedIn(){
return false;
}
}

describe('Home', () => {
beforeEach(() => TestBed.configureTestingModule({
providers: [
BaseRequestOptions,
{ provide: Router, useClass: MockRouter },
HomeComponent,
{ provide: AuthenticationService, useClass: MockAuth }
]
}));

it('should navigate to login', inject([HomeComponent], (home: HomeComponent) => {
let navigate = jasmine.createSpy('navigate');
expect(navigate.calls.mostRecent().args[0]).toEqual(['/login']);
}));
});

但我收到错误:

TypeError: undefined is not an object (evaluating 'navigate.calls.mostRecent().args') in config/spec-bundle.js (line 41757)

我认为 Jasmine spy 是正确的方法,但我错过了一些东西——我做错了什么?

最佳答案

您应该将 spy 添加到 MockRouter 类中。这样 spy 就可以监视 Router

中的 navigate 调用
class MockRouter {
navigate = jasmine.createSpy('navigate');
}

describe('Home', () => {
let mockRouter;
let fixture;
let component: HomeComponent;

beforeEach(() => {
mockRouter = new MockRouter();
TestBed.configureTestingModule({
declarations: [ HomeComponent ]
providers: [
BaseRequestOptions,
{ provide: Router, useValue: mockRouter },
{ provide: AuthenticationService, useClass: MockAuth }
]
});
fixture = TestBed.createComponent(HomeComponent);
component = fixture.createComponent;
});

it('should navigate to login', () => {
// calls component.ngOnInit
fixture.detectChanges();

// assuming some navigation has been done
expect(mockRouter.navigate).toHaveBeenCalledWith(['/login']);
});
});

注意事项:

  • HomeComponentdeclarations 中,不在 providers
  • 我们在测试中持有对 mock 的引用,并在配置时使用 useValue 而不是 useClass

关于unit-testing - Jasmine route spy - undefined 不是对象(评估 'navigate.calls.mostRecent().args' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40251319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com