在Jasmine中测试角度异步/等待功能

时间:2019-04-29 04:42:54

标签: javascript angular typescript jasmine

我正在尝试创建一个单元测试来测试使用async/await关键字调用$q的角度组件。我想模拟$q的返回值,并让我的组件对该模拟数据进行一些处理。不幸的是,似乎数据没有被正确模拟,并且我正在检查其值的组件部分返回null,因为它们从未生成。

我已经对茉莉花/角形中的异步功能的单元测试进行了一些研究:

http://www.bradoncode.com/blog/2015/07/13/unit-test-promises-angualrjs-q/

Angular 1.5 && Async/Await && jasmine tests

但是还没有成功。添加$scope.$apply()方法会带来新的问题,即必须模拟平台所进行的许多其他$httpbackend调用。嘲笑要从$ q返回的承诺也没有帮助。

我要测试的功能:

this.resolver(async () => {
     const preliminaryResults = await this.$q.all(dataPromises);
     const results = await this.checkDataAmount(preliminaryResults, restangularQueryable, startDate, endDate);

// Do some processing on the data

我的单元测试如下:

it('should support calendar preview', () => {
            component.alert.whenCondition = 'CALENDAR';
            const response = [{
                timestamps: [1, 2, 360000000],
                timestampsWithValues: [],
                values: [1, 2, 3]
            }, {
                values: {
                    avg: 1
                }
            }];
            const promise = new Promise((resolve, reject) => {
                resolve(response);
            });
            spyOn(component, 'checkDataAmount').and.returnValue(promise);
            spyOn($q, 'all').and.returnValue(promise);
            component.getAlertPreviewConfig();
            expect(component.chartConfig.yAxis.plotLines[0].value).toBe(5);
            expect(component.chartConfig.yAxis.max).toBe(5.5);
            expect(component.chartConfig.series[0].data).toEqual([{x: 1, y: 5}, {x: 2, y: 5}, {x: 172800001, y: 5}, {x: 172800002, y: 5}, {x: 360000000, y: 5}]);
            expect(component.chartConfig.series[1].data).toEqual([{x: 1, y: 0}, {x: 2, y: 0}, {x: 2, y: 2}, {x: 1, y: 2},
                {x: null, y: null}, {x: 1, y: 5}, {x: 2, y: 5}, {x: 2, y: 1005}, {x: 1, y: 1005}, {x: null, y: null}]);
            expect(component.chartConfig.series[2].data).toEqual([{x: 172800001, y: 0}, {x: 172800002, y: 0}, {x: 172800002, y: 2}, {x: 172800001, y: 2},
                {x: null, y: null}, {x: 172800001, y: 5}, {x: 172800002, y: 5}, {x: 172800002, y: 1005}, {x: 172800001, y: 1005}, {x: null, y: null}]);
        });

我希望运行测试后component的属性不会为空。具体来说,我希望chartConfig不为null。我跟踪了测试,发现代码中的await调用之后测试停止了。我在这里做什么错了?

0 个答案:

没有答案
相关问题