【问题标题】:Failed unit test case (JASMINE)失败的单元测试用例 (JASMINE)
【发布时间】:2021-09-29 14:34:53
【问题描述】:

我有一个函数,我正在尝试编写一个因错误而失败的规范

Unhandled promise rejection: [object Object]

功能:

someFunction(a,b,c) {
    var dfd = q.defer();
    this.getInfo(b,c).then((data)=> {
       //do Something
    
      dfd.resolve(data);
    }).catch((error)=> {
       dfd.reject(error)
    })
    
    return dfd.promise;
}

规格:

describe( 'SomeFunction', () => {
    it( 'should reject when getInfo request fails',  ( done ) => {
        spyOn( utility, 'getInfo' ).and.callFake( async () => {
            var deferred = q.defer();               
            deferred.reject( { error: 500 } );
            return deferred.promise;
        });
        let promise =  utility.someFunction( a,b,c );
        expect(utility.getInfo).toHaveBeenCalled();
        promise.then().catch( function ( data:any) {
            expect( data ).toEqual( { error: 500 } );
        } ).finally( done );
    });

我想在这里写下拒绝的测试用例,然后得到错误未处理的承诺拒绝。

如果我在这里做错了什么,请告诉我。

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript typescript unit-testing jasmine karma-jasmine


    【解决方案1】:

    你应该使用rejectWith(value):

    告诉间谍在被调用时返回一个带有指定值的拒绝承诺。

    监视utility.getInfo() 方法。由于utility.someFunction的返回值是一个promise,你应该使用expectAsync(actual)来创建一个异步期望。

    index.ts:

    import q from 'q';
    
    const utility = {
      someFunction(a, b, c) {
        var dfd = q.defer();
        this.getInfo(b, c)
          .then((data) => {
            dfd.resolve(data);
          })
          .catch((error) => {
            dfd.reject(error);
          });
        return dfd.promise;
      },
      async getInfo(b, c) {
        return 'real data';
      },
    };
    
    export { utility };
    

    index.test.ts:

    import { utility } from './';
    
    describe('69378465', () => {
      it('should pass', async () => {
        spyOn(utility, 'getInfo').and.rejectWith({ error: 500 });
        await expectAsync(utility.someFunction('a', 'b', 'c')).toBeRejectedWith({ error: 500 });
        expect(utility.getInfo).toHaveBeenCalled();
      });
    });
    

    测试结果:

    Test Suites & Specs:
    
    1. 69378465
       ✔ should pass (11ms)
    
    >> Done!
    
    
    Summary:
    
    ?  Passed
    Suites:  1 of 1
    Specs:   1 of 1
    Expects: 2 (0 failures)
    Finished in 0.017 seconds
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-08
      • 2016-02-12
      • 1970-01-01
      • 2012-02-28
      • 1970-01-01
      • 1970-01-01
      • 2022-09-30
      • 1970-01-01
      相关资源
      最近更新 更多