簡體   English   中英

Angular 2-Karma無法找到外部模板或樣式文件

[英]Angular 2 - Karma cannot find the external template or style file

文件結構(這是來自Angular 2官方網站的quickstarter項目):

在此處輸入圖片說明

剛開始時,啟動Karma時出現錯誤,提示無法在/ @ angular /下找到兩個文件。

我發現我必須更改systemjs.config.js中的路徑才能使其工作:

/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': '/base/node_modules/'  <<<<<<<------ Vincent: to be able to run the test, 
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      'app': 'app',

      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

      // other libraries
      'rxjs':                      'npm:rxjs',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        defaultExtension: 'js',
        meta: {
          './*.js': {
            loader: 'systemjs-angular-loader.js'
          }
        }
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);

因此,至少Karma現在可以運行,我可以運行其他測試。 但是,組件測試失敗,因為它找不到組件的外部模板和樣式文件。

在此處輸入圖片說明

我曾經能夠通過在Chrome中打開http:// localhost:9876 / base / src / app / app.component.html來打開html,但現在找不到了。

嘗試了以下答案: https : //stackoverflow.com/a/39909929/3634727 ,以及此處的所有解決方案: 錯誤:未被發現(承諾):無法加載login.component.html ,沒有運氣。

我的第一個問題是,讓我們擱置設置,在瀏覽器中打開app.component.html的正確URL是什么? http:// localhost:9876 / src / app / app.component.html不起作用。

我已解決它,並希望分享我發現的內容。

首先,要回答我自己的第一個問題,URI( http:// localhost:9876 / base / src / app / app.component.html )是正確的,Karma通過此URI解決了文件。 重新啟動PC后,可以直接在Chrome中打開它來訪問它。

Karma提供的根路徑與用於運行應用程序的根路徑不同,因此,一個好的做法是在組件的注釋中為外部模板和樣式文件使用相對路徑,例如:

// imports...

@Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    providers: [RuntimeSettingsService]
})
export class AppComponent implements OnInit {
    //...
}

在兩種情況下都可以使用根路徑的設置。 有關更多詳細信息,請參閱此博客: 使用Jasmine&Karma在Angular 2快速入門示例上運行單元測試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM