Jasmine:期望在异步函数中抛出错误

时间:2017-07-03 00:21:46

标签: angular unit-testing typescript jasmine angular2-services

我的angular2应用程序中有一个异步函数,我想编写一个单元测试。想象一下我的功能是这样的:

myFunc(a: int): Promise<void> {
    if (a == 1)
        throw new Error('a should not be 1');

    let body = {
        value: a
    };
    return apiService.patch('/url/', JSON.stringify(body)).toPromise();
}

现在,我正在考虑检查是否有条件。我尝试了以下代码;但是,这个测试总是失败,因为我的代码实际上并没有等待任何结果:

it('should throw error if a = 1', () => {
    expect(() => {
        mySerivce.myFunc(1);
    }).toThrow(new Error('a should not be 1'));
})

我不知道应该如何为这些类型的逻辑编写单元测试......

3 个答案:

答案 0 :(得分:3)

您可以使用try catch。

这就是我提出的内容,也是Github问题跟踪器中茉莉花的建议。

https://github.com/jasmine/jasmine/issues/1410

function double(a: number): Promise<number> {
   if (a === 1) {
       throw new Error('a should not be 1')
   }

   return new Promise(function (resolve, reject) {
       setTimeout(resolve, 100, a * 2 )
   })
}

describe('test double', () => {
    it('should double any number but 1', async() => {
        const result = await double(2);
        expect(result).toBe(4)
    });

    it('should throw an error', async() => {
        let error;
        try {
            await double(1)
        } catch (e) {
            error = e;
        }
        const expectedError = new Error('a should not be 1');
        expect(error).toEqual(expectedError)

    })
});

我还给自己写了一个小帮手

async function unpackErrorForAsyncFunction(functionToTest: Function, ...otherArgs: any[]): Promise<Error> {
    let error;
    try {
        const result = await functionToTest(...otherArgs);
    } catch (e) {
        error = e;
    }
    return error;
}

function double(a: number): Promise<number> {
    if (a === 1) {
        throw new Error('a should not be 1')
    }

    return new Promise(function (resolve, reject) {
        setTimeout(resolve, 100, a * 2 )
    })
}

function times(a: number, b: number): Promise<number> {
    if (a === 1 && b === 2) {
        throw new Error('a should not be 1 and 2')
    }

    return new Promise(function (resolve, reject) {
        setTimeout(resolve, 100, a * b )
    })
}

describe('test times and double with helper', () => {
    it('double should throw an error with test helper', async() => {
        const result = await unpackErrorForAsyncFunction(double, 1);
        const expectedError = new Error('a should not be 1');

        expect(result).toEqual(expectedError)
    });

    it('times should throw an error with test helper', async() => {
        const result = await unpackErrorForAsyncFunction(times, 1, 2);
        const expectedError = new Error('a should not be 1 and 2');

        expect(result).toEqual(expectedError)
    });
});

答案 1 :(得分:0)

如今,茉莉花(3.3+)原生支持:

https://jasmine.github.io/api/3.4/async-matchers.html

package main

import "fmt"

func main() {
    ch := make(chan int)
    ch <- 1

    fmt.Println(<-ch)
}

答案 2 :(得分:-2)

您可以断言方法是否使用间谍抛出错误:

import Spy = jasmine.Spy;
it('should...', () => {
 (mySerivce.myFunc as Spy).and.Callthrough();
 mySerivce.myFunc(1);
 expect(mySerivce.myFunc).toThrow();
});

可选择使用fakeASync解决&#34; racecondition&#34;麻烦。

我希望它有所帮助。