如何解决history.back 在 Karma 中的行为不符合预期
当我运行这样的基本测试用例时:
fdescribe('Browser back button',() => {
fit('should return to previous',async () => {
const originalHref = window.location.href;
window.history.pushState({},'Test','/test');
window.history.back(); // This doesn't seem to be working.
expect(window.location.href).toEqual(originalHref);
});
我收到错误消息“预期‘http://localhost:9876/test’等于‘http://localhost:9876/context.html’。”很明显 pushState() 有效,但 back() 没有。
Karma 在内部 iframe 中运行测试。当我将前三行按顺序粘贴到浏览器的 JavaScript 控制台中时,导航按预期工作。所以在这种情况下,窗口的行为和内部 iframe 的行为之间一定有什么不同。
这是 Chrome 上的 Karma 5.1。
有什么想法吗?
解决方法
问题在于 history.back()
API 是异步的
这个方法是异步的。为 popstate
事件添加一个侦听器,以确定导航何时完成。
所以导航返回被触发但测试没有等待它完成并且检查失败。
我们需要通过添加 done
参数将测试转换为异步测试(这是我知道的一种方法,也许还有其他方法)。并使用 popstate
事件处理程序等待导航并完成测试。
fdescribe('Browser back button',() => {
fit('should return to previous',(done) => {
const originalHref = window.location.href;
window.history.pushState({},'Test','/test');
window.history.back(); // gets executed asynchonously
window.addEventListener('popstate',() => {
// history.back() is done now
expect(window.location.href).toEqual(originalHref);
done();
})
});
});
,
Vitalii 的答案是最普遍适用的答案,因为它仅依赖于浏览器内置程序。这是基于 Angular 用户的代码的基本套件。
import { ComponentFixture,TestBed } from '@angular/core/testing';
import { MyComponent } from './my.component';
import { Location } from '@angular/common';
describe('MyComponent',() => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ MyComponent ],})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create',() => {
expect(component).toBeTruthy();
});
fdescribe('Browser back button',() => {
let location: Location;
let currentUrl: string;
const previousUrl = '/test';
beforeEach(() => {
location = TestBed.inject(Location);
currentUrl = location.normalize(window.location.href);
location.go(previousUrl);
location.go(currentUrl);
});
afterEach(() => location.go(currentUrl));
fit('should return to previous',done => {
location.subscribe(e => {
expect(e.url).toEqual(previousUrl);
done();
});
location.back();
});
});
});
要自定义后退按钮的行为,请重命名“应该返回上一个”以描述您希望该按钮执行的操作,并相应地更新测试。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。