繁体   English   中英

失败的单元测试用例 (JASMINE)

[英]Failed unit test case (JASMINE)

我有一个 function,我正在尝试为其编写一个失败并出现错误的规范

Unhandled promise rejection: [object Object]

Function:

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 );
    });

我想在这里写拒绝的测试用例,但随后得到未处理的错误 promise 拒绝。

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

任何帮助,将不胜感激。

你应该使用rejectWith(value)

告诉间谍在调用时返回一个 promise 拒绝指定值。

监视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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM