1/* 2 * Copyright (c) 2025 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import { AssertResult } from '../modal/assertModel'; 17import { AnyType } from '../types/common'; 18 19export function assertPromiseIsRejectedWithError( 20 actualPromise: Promise<AnyType>, 21 expectedValue: string[] 22): Promise<AssertResult> { 23 return actualPromise.then<AssertResult, AssertResult>( 24 (): AssertResult => { 25 return { 26 pass: false, 27 message: 'Expected a promise to be rejected but actualValue is resolve', 28 }; 29 }, 30 (actualValue: AnyType): AssertResult => { 31 return matchError(actualValue, expectedValue); 32 } 33 ); 34} 35 36function matchError(actualValue: AnyType, expectedValue: string[]): AssertResult { 37 const errorType = Class.of(actualValue as object).getName(); 38 const errorTypeArr = errorType.split('.'); 39 const errType = errorTypeArr[errorTypeArr.length - 1]; 40 if (expectedValue.length == 1) { 41 if (errType === expectedValue[0]) { 42 return { pass: true, message: 'actual error type is ' + errorType + '.' }; 43 } else { 44 return { pass: false, message: `except error type is ${expectedValue[0]},but actual is ${errorType}.` }; 45 } 46 } else if (expectedValue.length == 2) { 47 if ( 48 (expectedValue[0] === '' || errType === expectedValue[0]) && 49 (actualValue as Error).message === expectedValue[1] 50 ) { 51 return { pass: true, message: 'actual error message is ' + (actualValue as Error).message + '.' }; 52 } else if ( 53 expectedValue[0] !== '' && 54 errType !== expectedValue[0] && 55 (actualValue as Error).message === expectedValue[1] 56 ) { 57 return { pass: false, message: `expect error type is ${expectedValue[0]},but actual is ${errorType}.` }; 58 } else if ( 59 (expectedValue[0] === '' || errType === expectedValue[0]) && 60 (actualValue as Error).message !== expectedValue[1] 61 ) { 62 return { 63 pass: false, 64 message: `expect error message is ${expectedValue[1]},but actual is ${(actualValue as Error).message}.`, 65 }; 66 } else { 67 return { pass: false, message: 'expect error type and message are incorrect.' }; 68 } 69 } else { 70 return { pass: false, message: 'Up to two parameters are supported.' }; 71 } 72} 73