【问题标题】:Expected valuable after setTimeout in which is set在设置的 setTimeout 之后预期有价值
【发布时间】:2019-04-05 11:46:08
【问题描述】:

我无法在 setTimeout 中将预期值设置为相等。 我有两个有价值的是: 常量第一 = 0; 常量秒 = 0;

但是那个抛出错误是 Uncauth TypeError: You provide 'undefined' where a stream is expected。您可以提供 Observable、Promise、Array 或 Interable。

setNumber() {
   setTimeout(() => {
     first = 12;
     second = 1235
}, 250);

it('Should execute setNumber', fakeAsync(() => {`
   setTimeout(() => {
     expected(first).toEqual(12);
     expected(second ).toEqual(1235);
   }, 251)
}))

【问题讨论】:

    标签: javascript angular unit-testing


    【解决方案1】:

    在 fakeAsync 函数中使用 tick() 来模拟超时。像这样的东西:

    it('Should execute setNumber', fakeAsync(() => {
        let first;
        let second;
    
        setTimeout(() => {
          first = 12;
          second = 1235;
        }, 250);
    
        tick(251);
    
        expect(first).toEqual(12);
        expect(second).toEqual(1235);
      }));
    

    为了理解,勾选249,测试会失败。

    it('Should execute setNumber', fakeAsync(() => {
        let first;
        let second;
    
        setTimeout(() => {
          first = 12;
          second = 1235;
        }, 250);
    
        tick(249);
    
        expect(first).toEqual(12);
        expect(second).toEqual(1235);
      }));
    

    希望我能帮到你:)

    【讨论】:

    • 当我听从你的建议时。但这是错误的。据我了解,当勾选 250 时,它尚未设置。但在勾选 251 时,测试可以为真。但我不知道如何设置expected after timeout run event clear timeout并再次设置
    • 我不太明白你想要什么。你能写一个例子吗?
    • 我很抱歉我的回复晚了。我的例子是:在 250 中,第一个将设置为 12,在 251 中,我希望第一个等于 12。但我不知道要测试它。
    猜你喜欢
    • 2015-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多