[英]Testing Typescript Generated Classes with node.js, Mocha and mocha-jsdom?
我想從bash運行單元測試,以使用mocha和mocha-jsdom測試我的Typescript生成的Javascript類。 我使用mocha-jsdom是因為我想在測試中模擬dom,但要從bash運行單元測試。
我已經看到了一些示例,它們在瀏覽器中將前端測試框架用於摩卡,但是我還沒有看到它們在bash中運行的任何示例。
看來我無法在Mocha單元測試中包含從Typescript生成的Javascript類。
var jsdom = require('../../index');
require('../../src/js/acct/AccountManager.js');
describe('GenerateHTML', function() {
describe('#generateHTML()', function() {
jsdom()
it('should generate a table', function() {
var vahm = new VerticalAccountHTMLManager(document, "testId");
expect($("#testId")[0]).eql("table");
});
});
});
有什么方法可以將仍在bash中運行的創建類的函數導入到mocha單元測試中?
因此,讓我們從執行測試開始。 為了執行測試,您有幾種選擇:
karma
。 Karma是JavaScript測試人員。 實際上,您在karma.config.js
文件中指定了要執行的所有測試,它將執行所有測試。 您還具有watch
功能,該功能使您可以在每次更改代碼時執行測試 package.json
文件的script屬性內,您指定命令test
並將該命令與該腳本關聯,以便針對所有測試執行mocha。 然后您可以輸入npm test
來npm test
Gulp
, Grunt
等...。您可以指定一個任務來觸發測試,然后運行該任務,例如提供gulp mytask
命令 我的建議是目前直接使用node.js。 它使事情變得容易。
關於TypeScript,您可以直接將Mocha與TypeScrit結合使用,而無需使用JavaScript。 我建議您將摩卡咖啡與chai,chai-promise和sinon集成。 Chai是一個斷言庫。 Chai-as-promise可讓您測試promise和sinon以測試功能和方法。
這是我上面所說的test命令的package.json
示例:
"scripts": {
"test": "find ./src -name '*spec.ts' | xargs mocha -r ts-node/register"
}
在這一行,您將執行所有以*spec.ts
結尾的文件。 ts-node是一個非常有用的節點插件,它允許您直接通過ts-node myfile.ts
命令運行ts。
關於要包含在package.json
的依賴項,這里是一個有用的列表:
"devDependencies": {
"@types/chai": "^3.5.0",
"@types/chai-as-promised": "^0.0.30",
"@types/mocha": "^2.2.40",
"@types/node": "^7.0.12",
"@types/sinon": "^2.1.2",
"chai": "^3.5.0",
"chai-as-promised": "^6.0.0",
"husky": "^0.13.3",
"mocha": "^3.2.0",
"sinon": "^2.1.0",
"ts-node": "^3.0.2",
"typings": "^2.1.1"
}
關於如何將Mocha集成到測試中,這里是一個規范文件的聲明,您可以將其用作模式:
// imports of testing libraries
import * as mocha from 'mocha';
import * as chai from 'chai';
import * as chaiAsPromised from 'chai-as-promised';
import sinon = require('sinon');
// import of the source files to be tested
import Main from './Main'; // an example
// testing inits
chai.use(chaiAsPromised);
const expect = chai.expect;
const assert = chai.assert;
const should = chai.should();
您可以嘗試看一下這個倉庫。 有一個非常簡單的項目,帶有TypeScript和我上面說過的所有測試庫。 它仍在進行中,我還沒有時間完成它,因此主README.md也未更新。 但是,如果您克隆項目或下載源代碼,則可以完全了解我上面所說的所有內容,並可以在測試中使用所有方法的說明:
https://github.com/quirimmo/testing-typescript-mocha-chai-sinon
希望對您有所幫助! 如有任何疑問,請通知我!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.