[英]Read a HTML file in a Karma+Jasmine test
我有一個Angular控制器,它定義了一個包含50多個字段名稱的數組。 其中每個都應出現在HTML文件中,因為輸入的id和ng模型都存在。 我想通過閱讀和解析HTML文件測試我是否沒有輸入拼寫錯誤。 因為我需要獲得數組,所以Karma + Jasmine測試似乎是理想的(使用量角器我無法得到它)。 測試這個的好方法是什么?
對於FileReader
和$http.get
都沒有輸入成功或錯誤函數,而使用XMLHttpRequest
我只得到一個空字符串。
我已經添加了一行
pattern: 'app/views/*.html', watched: false, included: false, served: true}
到karma.conf.js,匹配我想要讀取的文件。
任何幫助是極大的贊賞。
1.您可以使用以下預處理器來呈現html
將以下內容添加到karma.config.js中:
ngHtml2JsPreprocessor : {
moduleName:'templates'
},
2.使用angular的$ compile服務並創建要測試的html並將其添加到dom。 然后你可以對那個html執行任何測試
var $body=$('$body');
afterEach(
$body.empty();
);
您可以使用jasmine-jquery
將HTML-snippets加載為fixture。 不要懷疑這個名字,因為該庫還添加了許多自定義茉莉花匹配器 ,它們與jQuery結合使用非常有用。
要使用它,請將您的karma配置文件中的以下內容添加到files
數組中:
// this is the path to your library if installed via bower
'../bower_components/jasmine-jquery/lib/jasmine-jquery.js',
// make the views available to the locally by karma started webserver
{pattern: 'views/*.html', watched: true, served: true, included: false},
對於測試,您必須定義視圖的路徑並明確加載它們:
beforeEach(function () {
jasmine.getFixtures().fixturesPath = "base/views"; // path to your templates
jasmine.getFixtures().load('myHtmlSnippet.html'); // load a template
});
這會將帶有id jasmine-fixtures
的div
直接加載到運行測試的瀏覽器body
中。 加載的夾具將插入div#jasmine-fixtures
。 然后你可以使用jQuery或vanilla javascript簡單地訪問它們。
我有這樣的示例問題后調用“服務器”-data並且不使用模型服務。 我偶然發現了這個條目: E2E模擬$ httpBackend實際上並沒有為我傳遞
工作正常,你可以使用$ http.get並檢查你的數據。
如果您正在使用promises,請嘗試以下操作: https : //github.com/ThomasBurleson/jasmine-as-promised
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.