你可以使用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)
});
});