使用Jasmine在Angular中测试异步功能的问题

问题描述

我正在用Jasmine对Ionic 4应用程序进行单元测试。目前,我在运行几乎所有测试时都遇到错误,因为我对async / await函数做错了。我得到的错误是:“错误:超时-异步功能未在5000毫秒内完成。”我已将此timeout_interval更改为另一个更大的数字,但仍然收到此错误。

我的代码是:

beforeEach(async(() => {
  const storage = new Storage({         
    // Define Storage
    name: '__mydb',driverOrder: ['indexeddb','sqlite','websql']
  });  
    
  component = new HomepagePage(storage);

  TestBed.configureTestingModule({
    declarations: [ HomepagePage ],imports: [
      IonicModule.forRoot(),RouterTestingModule,IonicStorageModule.forRoot()
    ]
  }).compileComponents();

  fixture = TestBed.createComponent(HomepagePage);
  component = fixture.componentInstance;
  fixture.detectChanges();
}));

it('should create',async () => {
  let home = jasmine.createSpyObj('home_spy',['getprice'])
  const result = await home.getprice
  expect(component).toBeTruthy();
});

describe('before logged in',() => {
  let home = jasmine.createSpyObj('home_spy',['getprice'])
    
  it('shows the price',async () => {
    const result = await home.getprice
    expect(home.getprice.length).toEqual(2);
  });
});

我的应用在使用时运行正常。但是,错误可能出在代码本身中吗? getprice()函数的示例是:

async getprice() {
    var price_eth :number
    var price_btc :number

    try {
        var url_btc = "https://api.binance.com/api/v1/klines?symbol=BTCUSDT&interval=1m";
        var url_eth = "https://api.binance.com/api/v1/klines?symbol=ETHUSDT&interval=1m"
        const btc = await axios.get(url_btc)
        const eth = await axios.get(url_eth)

        if (btc.data.length != 0 && eth.data.length != 0) {
           this.loaded = 'yes'
        } else { 
            this.loaded='no'
        }
        this.time = new Date(btc.data[btc.data.length-1][0]).toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1");
        price_btc = Math.floor(btc.data[btc.data.length-1][1])
        price_eth = Math.floor(eth.data[eth.data.length-1][1])

       //These global variables are declared so they display the price but they are not used for any other functions.
       this.glob_price_btc = price_btc
       this.glob_price_eth = price_eth

       return {
        'price_btc':price_btc,'price_eth':price_eth
       }

    } catch {
        this.loaded = 'no';
        return
    }
}

解决方法

我认为您误解了功能beforeEach()beforeEach()应该用于设置测试环境,并且在执行单元测试之前将被调用。 这是一个如何更正确设置超时时间的示例。

describe("xyz test suite",() => {
    //called before every unittest
    beforeEach(function() {
        //Do setup stuff
    });
    
    it('shows the price',async () => {
        const result = await getSomething()
        expect(result).toEqual(2);
    });

},10000 <- Timeout in milliseconds)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...