我有一个简单的静态视图,我想为其编写测试:
<div class="landing-page">
<app-cover>
<app-stack [large]="true">
<app-center>
<img src="assets/images/logo.svg" />
</app-center>
<app-center>
<p>
Try matching the employee to their photo.
</p>
</app-center>
<app-center>
<app-button routerLink="namegame">
Play!
</app-button>
</app-center>
</app-stack>
</app-cover>
</div>
我能够断言<p>
标签和<button>
的文本很准确。但是,我在编写按钮行为的单元测试时遇到麻烦,例如当我单击按钮时,我导航到/namegame
路线。
我从业力中看到的消息确实令人困惑:
Chrome 83.0.4103.106 (Mac OS 10.15.5) NamegameComponent navigates to /namegame when the "Play"
button is clicked FAILED
Expected spy navigateByUrl to have been called with:
[ '/namegame', <jasmine.anything> ]
but actual calls were:
[ /namegame, Object({ skipLocationChange: false, replaceUrl: false, state: undefined }) ].
Call 0:
Expected $[0] = /namegame to equal '/namegame'.
测试代码:
// ... imports ...
describe('NamegameComponent', () => {
let component: LandingPageComponent;
let fixture: ComponentFixture<LandingPageComponent>;
let router: Router;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule.withRoutes([])],
declarations: [
LandingPageComponent,
CenterComponent,
CoverComponent,
StackComponent,
ButtonComponent,
],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LandingPageComponent);
component = fixture.componentInstance;
router = TestBed.inject(Router);
fixture.detectChanges();
});
// ... other tests ...
it('navigates to /namegame when the "Play" button is clicked', () => {
const navSpy = spyOn(router, 'navigateByUrl');
const button = fixture.nativeElement.querySelector('app-button');
button.click();
expect(navSpy).toHaveBeenCalledTimes(1);
expect(navSpy).toHaveBeenCalledWith(`/namegame`, jasmine.anything());
});
});
有什么主意为什么断言不匹配?报价有问题吗?
答案 0 :(得分:1)
原来的问题是,navigateByUrl
是用UrlTree
而不是像我最初期望的那样的字符串来调用的。
这些断言之一将起作用:
// matching the UrlTree directly
expect(navSpy).toHaveBeenCalledWith(
router.createUrlTree(['/namegame']),
jasmine.anything()
);
或
// explicitly convert the UrlTree to a string before comparison
expect(navSpy.calls.mostRecent().args[0].toString()).toEqual('/namegame');
答案 1 :(得分:0)
我只能假设是因为您使用的是反引号而不是普通引号。试试:
expect(navSpy).toHaveBeenCalledWith('/namegame', jasmine.anything());