1/* 2 * Copyright (c) 2023 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 {before} from 'mocha'; 17import {assert} from 'chai'; 18import {createSourceFile, ScriptTarget, SourceFile} from 'typescript'; 19 20import {collectExistNames, OhPackType} from '../../../src/utils/TransformUtil'; 21import {findOhImportStatement} from '../../../src/utils/OhsUtil'; 22 23describe('test for TransformUtil', function () { 24 let sourceFile: SourceFile; 25 26 before('init ast for source file', function () { 27 const fileContent = ` 28 class Demo{ 29 constructor(public title: string, public content: string, public mark: number) { 30 this.title = title 31 this.content = content 32 this.mark = mark 33 } 34 } 35 `; 36 37 sourceFile = createSourceFile('demo.js', fileContent, ScriptTarget.ES2015, true); 38 }); 39 40 describe('test for function collectExistNames', function () { 41 it('test collectExistNames', function () { 42 const nameSets = collectExistNames(sourceFile); 43 const targetNames = ['Demo', 'title', 'content', 'mark']; 44 45 assert.strictEqual(nameSets.size, targetNames.length); 46 targetNames.forEach((value) => { 47 assert.isTrue(nameSets.has(value)); 48 }); 49 }); 50 }); 51 52 describe('test for function findOhImportStatement', function () { 53 it('find oh import in esmodule', function () { 54 const fileContent = `var hilog = globalThis.requireNapi('hilog') || 55 (isSystemplugin('hilog', 'ohos') ? 56 globalThis.ohosplugin.hilog : isSystemplugin('hilog', 'system') ? 57 globalThis.systemplugin.hilog : undefined); 58 `; 59 60 const source = createSourceFile('demo2.js', fileContent, ScriptTarget.ES2015, true); 61 const statement = source.statements[0]; 62 const ohPackType = findOhImportStatement(statement, '@ohos.hilog'); 63 64 assert.strictEqual(ohPackType, OhPackType.ES_MODULE); 65 }); 66 67 it('find oh import in jsbundle', function () { 68 const fileContent = `var _ohos = _interopRequireDefault(requireModule('@ohos.hilog'))`; 69 const source = createSourceFile('demo2.js', fileContent, ScriptTarget.ES2015, true); 70 const statement = source.statements[0]; 71 const ohPackType = findOhImportStatement(statement, '@ohos.hilog'); 72 73 assert.strictEqual(ohPackType, OhPackType.JS_BUNDLE); 74 }); 75 }); 76});