angularjs - 如何测试使用 async/await 的方法?

标签 angularjs unit-testing jasmine ecmascript-2017

我看过很多关于如何在单元测试中使用 async/await 的文章,但我的需求正好相反。

您如何为使用 async/await 的方法编写测试?

我的规范在“等待”行之后无法访问任何代码。具体来说,规范在两个方面失败了。

1) HelloWorld.otherCall返回 undefined 而不是我指定的返回值

2) HelloWorld.processResp永远不会被调用

class HelloWorld {

    async doSomething(reqObj) {
        try {
           const val = await this.otherCall(reqObj);
           console.warn(val); // undefined
           return this.processResp(val);
        }
    }

}

describe('HelloWorld test', function () {

    let sut = new HelloWorld(); //gross simplification for demo purposes

    describe('doSomething()', function () {
        beforeEach(function mockInputs() {
           this.resp = 'plz help - S.O.S.';
        });

        beforeEach(function createSpy() {
            spyOn(sut, 'otherCall').and.returnValue( $q.resolve(this.resp) );
            spyOn(sut, 'processResp');
        });

        it('should call otherCall() with proper arguments', function () {
            //this test passes   
        });

        it('should call processResp() with proper arguments', function () {
           sut.doSomething({});
           $rootScope.$apply(); //you need this to execute a promise chain..

           expect(sut.processResp).toHaveBeenCalledWith(this.resp); 
           //Expected spy processResp to have been called with [ 'plz help SOS' ] but it was never called.
        });
    });
});

运行 angular 1.5 和 jasmine-core 2.6。

最佳答案

.then promise 的重载以处理 promise 或值,和 await是调用 then 的语法糖.

所以没有理由要求你的 spy 返回一个 promise ,甚至一个值。完全返回,即使 undefined , 应该触发 await开火,然后开始剩下的 async功能。

我相信你的问题是你没有等待 doSomething promise 在尝试测试它做了什么之前解决。像这样的事情应该会让你更有把握。

it('should call processResp() with proper arguments', async function () {
   await sut.doSomething({});
   // ...
});

关于angularjs - 如何测试使用 async/await 的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48346754/

相关文章:

javascript - 你如何使用 html/angularjs 保存图像文件?

angularjs - Google map setCenter 未正确将 map 居中

javascript - 如何为与 ASP .Net MVC 包装器一起使用的 Kendo UI 进行 TDD

unit-testing - 如何最好地对 Web 应用程序进行单元测试

node.js - 如何使用 jasmine-node 监视 Node 模块中的私有(private)函数?

javascript - AngularJS Jasmine 测试失败 : Failed to instantiate module

AngularJS:$watch 来自 Controller ,用于更改使用 ng-repeat 创建的属性

AngularJS:在隐藏的 DOM 元素上暂停 $digest 和观察者

javascript - 测试异步调用会在 Node JS 中抛出未处理的 promise 拒绝

angularjs - Jasmine 2.0 : Asynchronous test case