angular2:如何测试具有可观察时间间隔的组件

2024-01-11

我有一个幻灯片放映组件,它有一个幻灯片对象的输入数组,并显示每个幻灯片对象,只要它是在slide.time其本身。还有两个按钮,单击它们必须滑动到下一个项目并重置计时器。为了完成这项工作,我使用如下 Observables:

/**
 * a "SUBJECT" for pausing(restarting) the slider's auto-slide on user's click on left and right arrows
 * @type {Subject}
 */
private pauser = new Subject();

/**
 * the main observable for timer (before adding the pause/reset option)
 * @type {Observable<T>}
 */
private source = Observable
    .interval(1000)
    .timeInterval()
    .map(function (x) { /*return x.value + ':' + x.interval;*/ return x })
    .share();

/**
 * the final timer, which can be paused
 * @type {Observable<R>}
 */
private pausableSource = this.pauser.switchMap(paused => paused ? Observable.never() : this.source);

/**
 * the subscription to the timer which is assigned at OnInit hook , and destroyed at OnDestroy
 */
private subscription;

ngOnInit(){
    this.subscription = this.pausableSource.subscribe(() => {
        //doing changes to the template and changing between slides
    });
    this.pauser.next(false);
}

ngOnDestroy() {
    this.subscription.unsubscribe();
}

并且它工作正常。 现在为了测试这个组件,我在测试主机组件中给它一些数据,并想检查它的功能,如下所示:

it("should show the second (.slidingImg img) element after testHost.data[0].time seconds 
    have passed (which here, is 2 seconds)", () => {
    //testing
});

我尝试了在文档或互联网上的任何地方找到的许多东西,但它们都不适合我。问题是我无法以可观察计时器执行下一步操作的方式模拟时间的流逝,而且就像没有时间过去一样。对我来说没有用的两种方法是:

it("should show the second (.slidingImg img) element after testHost.data[0].time seconds 
    have passed (which here, is 2 seconds)", fakeAsync(() => {
    fixture.detectChanges();
    tick(2500);
    flushMicrotasks();
    fixture.detectChanges();
    let secondSlidingImg = fixture.debugElement.queryAll(By.css('.slidingImg'))[1].query(By.css('img'));
    expect(secondSlidingImg).toBeTruthy();
    //error: expected null to be truthy
}));

我从 angular2 文档得到这个。

and:

beforeEach(() => {
    fixture = TestBed.createComponent(TestHostComponent);

    testHost = fixture.componentInstance;

    scheduler = new TestScheduler((a, b) => expect(a).toEqual(b));

    const originalTimer = Observable.interval;
    spyOn(Observable, 'interval').and.callFake(function(initialDelay, dueTime) {
        return originalTimer.call(this, initialDelay, dueTime, scheduler);
    });
    // or:
    // const originalTimer = Observable.timer;
    // spyOn(Observable, 'timer').and.callFake(function(initialDelay, dueTime) {
    //     return originalTimer.call(this, initialDelay, dueTime, scheduler);
    // });
    scheduler.maxFrames = 5000;

});
it("should show the second (.slidingImg img) element after testHost.data[0].time seconds 
    have passed (which here, is 2 seconds)", async(() => {
    scheduler.schedule(() => {
        fixture.detectChanges();
        let secondSlidingImg = fixture.debugElement.queryAll(By.css('.slidingImg'))[1].query(By.css('img'));
        expect(secondSlidingImg).toBeTruthy();
        //error: expected null to be truthy
    }, 2500, null);
    scheduler.flush();
}));

我从这里得到了这种方法这个问题 https://stackoverflow.com/questions/39167415/unit-test-rxjs-observable-timer-using-typescript-karma-and-jasmine.

所以我迫切需要知道在单元测试中应该如何准确地模拟时间流逝,以便组件的可观察时间间隔真正触发......

版本:

angular: "2.4.5"
"rxjs": "5.0.1"
"jasmine": "~2.4.1"
"karma": "^1.3.0"
"typescript": "~2.0.10"
"webpack": "2.2.1"    

fakeAsync对于 RxJ 的某些情况不起作用。您需要手动移动 RxJ 中的内部计时器。沿着这些思路:

import {async} from 'rxjs/internal/scheduler/async';
...

describe('faking internal RxJs scheduler', () => {
  let currentTime: number;

  beforeEach(() => {
    currentTime = 0;
    spyOn(async, 'now').and.callFake(() => currentTime);
  });

  it('testing RxJs delayed execution after 1000ms', fakeAsync(() => {
    // Do your stuff
    fixture.detectChanges();
    currentTime = 1000;
    tick(1000);
    discardPeriodicTasks();

    expect(...);
  }));
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

angular2:如何测试具有可观察时间间隔的组件 的相关文章

  • Angular 2 路由器使用 Observable 进行解析

    Angular 2 RC 5 发布后引入了路由器解析 Here https angular io docs ts latest guide router html resolve guard使用 Promise 演示了示例 如果我使用 Ob
  • 如何向离子推送通知添加操作按钮?

    我想向离子推送通知添加一些操作按钮 我正在使用科尔多瓦pushv5 通知工作正常 但我不知道如何添加这些按钮 如何添加这些按钮 应在 POST 请求中添加操作按钮 registration ids my device id data tit
  • Django:出于测试目的阻止互联网连接

    我想确保我的单元测试不会尝试连接到互联网 有没有办法在连接时引发异常 有一个类似的问题Python 出于测试目的阻止网络连接 https stackoverflow com questions 18601828 python block n
  • Webpack 在 Angular 的 ng 服务中的作用

    我是 Angular 的新手 想知道当我们为应用程序提供服务时 Webpack 在幕后扮演什么角色 在最初的印象中 我开始知道 webpack 是一个构建和打包工具 它将所有必需的 JS 文件分组到单独的包中 然而 我无法找到 webpac
  • C# 模拟接口与模拟类

    我是 net 中的最小起订量框架的新手 根据我的在线研究 似乎有两种方法可以使用这个框架 要么模拟接口 要么模拟具体类 似乎在嘲笑具体类时 只有virtual方法可以被嘲笑 就我而言 我只想模拟实现接口的类的几个方法 例如 如果我们有以下内
  • Scala 的代码覆盖率工具 [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • 莫基托。验证方法参数是特定类

    我有一个方法 void putObject
  • 如何在 ngrx/effects 中执行 if/else 操作?

    我正在使用 ngrx effects 我想根据以下情况分派不同的操作foo商店里的状态 这就是我现在正在做的 Effect foo1 this updates whenAction Actions FOO filter obj gt obj
  • Xcode 6.4 Swift 单元测试无法编译:“GPUImage.h 未找到”“无法导入桥接标头”

    我的 Xcode 项目构建并运行良好 它有 Swift 和 Objective C 代码 它已安装 GPUImage 我向它添加了单元测试 现在它将不再编译 找不到 GPUImage h 文件 导入桥接标头失败 以下是我发现并尝试过的解决方
  • Angular4 - 滚动到锚点

    我正在尝试对同一页面上的锚元素进行简单的滚动 基本上 用户点击 尝试 按钮 它就会滚动到页面下方 ID 为 登录 的区域 现在 它正在与一个基本的id login a href login a 但它正在跳转到该部分 理想情况下 我希望它滚动
  • 使用文件 IO 的单元测试方法

    我正在努力养成编写单元测试的习惯 我之前写过一些 但它们通常都很基础 我想开始转向 TDD 因为我想提高质量我的代码 设计和结构 减少耦合 同时希望减少可测试构建的回归数量 我从一个相对简单的项目开始 生成的程序监视一个文件夹 然后对该文件
  • GoogleTest 枚举类的测试错误打印

    我正在使用 GoogleTest 版本 1 7 0 来测试我的 C 应用程序 我有一个枚举定义如下 namespace MyNamespace enum class MyEnum MyEnumValue MyEnumValue2 Googl
  • 如何在 Angular 2 应用程序中从 TypeScript/JavaScript 中的字符串获取类?

    在我的应用程序中 我有这样的内容 user ts export class User 现在 我这样做 应用程序组件 ts callAnotherFunction User 如果我将类名作为字符串 即 我该如何做到这一点 User 如果可能的
  • MatAutocomplete 值 X 显示

    我的自动完成显示具有以下定义的对象的值 export class Person id number name string cityName string 这是自动完成模板
  • Angular2:鼠标事件处理(相对于当前位置的移动)

    我的用户应该能够通过鼠标在画布中移动 或旋转 对象 当鼠标事件发生时 屏幕坐标用于计算与最后一个事件的增量 方向和长度 没什么特别的 mousedown 获取第一个坐标 mousemove 获取第n个坐标 计算deltaXY 按deltaX
  • 如何在 Angular 单元测试中模拟/触发 $routeChangeSuccess?

    给定一个附加到 routeChangeSuccess 事件的处理程序来更新 rootScope 上的 title 属性 rootScope on routeChangeSuccess function event current previ
  • 如何使用 Angular 2 动画实现翻转效果?

    我一直在我的项目中使用纯CSS翻转卡片 但这个解决方案不是合适的 有人可以通过点击按钮来呈现角度 2 的翻转吗 我在 angularjs 中找到了一个https codepen io Zbeyer pen oXQrZg https code
  • 在 Angular 中深度复制对象

    AngularJS 有angular copy 深度复制对象和数组 Angular 也有类似的东西吗 您还可以使用 JSON parse JSON stringify Object 如果它在你的范围内 那么它就存在于每个 Angular 组
  • 修剪日期格式 PrimeNG 日历 - 删除时间戳、角度反应形式

    我将以下内容推入我的反应形式 obj 中2016 01 01T00 00 00 000Z但我想要以下2016 01 01 有谁知道有一个内置函数可以实现上述目的 我已经搜索过文档here https www primefaces org p
  • 在停止调试时终止 VS Code 中的 ng 服务任务

    我有一个 Angular 项目 目前正在通过 chrome 调试器在 vs code 内进行调试 我的launch json uses preLaunchTask serve 其中服务定义于tasks json as ng serve 这样

随机推荐