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

Angularjs 如何测试使用async/await的方法?,angularjs,unit-testing,jasmine,ecmascript-2017,Angularjs,Unit Testing,Jasmine,Ecmascript 2017,我已经看过很多关于如何在单元测试中使用async/await的文章,但我的需求正好相反 如何为使用async/await的方法编写测试 我的规范在“等待”行之后无法到达任何代码。具体来说,规范在两个方面失败 1) HelloWorld.otherCall返回未定义的值,而不是我指定的返回值 2) HelloWorld.processResp从未被调用 class HelloWorld { async doSomething(reqObj) { try {

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

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

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

1)
HelloWorld.otherCall
返回未定义的值,而不是我指定的返回值

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。

jasmine有。你或许可以通过这种方式找到解决办法

就我个人而言,我认为你根本不应该测试这些方法

测试状态意味着我们正在验证测试中的代码是否返回正确的结果

测试交互意味着我们正在验证测试中的代码是否正确调用了某些方法

在大多数情况下,测试状态更好

以你为例,

async doSomething(reqObj) {
    try {
       const val = await this.otherCall(reqObj);
       return this.processResp(val);
    }
}
只要单元测试很好地涵盖了otherCall&processResp,您的产品就很好

e2e测试应涵盖“做某事”


您可以在的
上了解更多信息。然后,承诺的
被重载以处理承诺或值,而
wait
是调用
then
的语法糖

因此,你的间谍没有理由被要求返回一个承诺,甚至一个价值。返回时,即使
未定义
,也应触发
等待
触发,并启动
异步
函数的其余部分

我相信您的问题在于,您没有等待
doSomething
承诺在尝试测试它所做的事情之前得到解决。像这样的事情应该会让你在球场上表现得更好

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