문서의 이전 판입니다!
devrafalko / webpack-karma-jasmine
제안하는 package:
.js로 묶기 위한 karma-webpack and babel-loaderkarma-mocha-reporterkarma-jasmine-html-reporter예제를 위한 전체설명입니다.
npm install --save-dev webpack webpack-cli webpack-karma-jasmine npm install --save-dev @babel/cli @babel/core @babel/preset-env babel-loader npm install --save-dev jasmine-core karma karma-chrome-launcher npm install --save-dev karma-jasmine karma-jasmine-html-reporter karma-mocha-reporter karma-webpack
karma.conf.js의 추천설정
module.exports = function(config) { config.set({ //root path location to resolve paths defined in files and exclude basePath: '', //files/patterns to exclude from loaded files exclude: [], //files/patterns to load in the browser files: [ {pattern: 'tests/*.js',watched:true,served:true,included:true} /*parameters: watched: if autoWatch is true all files that have watched set to true will be watched for changes served: should the files be served by Karma's webserver? included: should the files be included in the browser using <script> tag? nocache: should the files be served from disk on each request by Karma's webserver? */ /*assets: {pattern: '*.html', watched:true, served:true, included:false} {pattern: 'images/*', watched:false, served:true, included:false} */ ], //executes the tests whenever one of the watched files changes autoWatch: true, //if true, Karma will run tests and then exit browser singleRun:false, //if true, Karma fails on running empty test-suites failOnEmptyTestSuite:false, //reduce the kind of information passed to the bash logLevel: config.LOG_WARN, //config.LOG_DISABLE, config.LOG_ERROR, config.LOG_INFO, config.LOG_DEBUG //list of frameworks you want to use, only jasmine is installed automatically frameworks: ['jasmine'], //list of browsers to launch and capture browsers: ['Chrome'/*,'PhantomJS','Firefox','Edge','ChromeCanary','Opera','IE','Safari'*/], //list of reporters to use reporters: ['mocha','kjhtml'/*,'dots','progress','spec'*/], //address that the server will listen on, '0.0.0.0' is default listenAddress: '0.0.0.0', //hostname to be used when capturing browsers, 'localhost' is default hostname: 'localhost', //the port where the web server will be listening, 9876 is default port: 9876, //when a browser crashes, karma will try to relaunch, 2 is default retryLimit:0, //how long does Karma wait for a browser to reconnect, 2000 is default browserDisconnectTimeout: 5000, //how long will Karma wait for a message from a browser before disconnecting from it, 10000 is default browserNoActivityTimeout: 10000, //timeout for capturing a browser, 60000 is default captureTimeout: 60000, client: { //capture all console output and pipe it to the terminal, true is default captureConsole:false, //if true, Karma clears the context window upon the completion of running the tests, true is default clearContext:false, //run the tests on the same window as the client, without using iframe or a new window, false is default runInParent: false, //true: runs the tests inside an iFrame; false: runs the tests in a new window, true is default useIframe:true, jasmine:{ //tells jasmine to run specs in semi random order, false is default random: false } }, /* karma-webpack config pass your webpack configuration for karma add `babel-loader` to the webpack configuration to make the ES6+ code readable by the browser */ webpack: { module: { rules: [ { test: /\.js$/i, exclude:/(node_modules)/, loader:'babel-loader', options:{ presets:['@babel/preset-env'] } } ] } }, preprocessors: { //add webpack as preprocessor to support require() in test-suites .js files './tests/*.js': ['webpack'] }, webpackMiddleware: { //turn off webpack bash output when running the tests noInfo: true, stats: 'errors-only' }, /*karma-mocha-reporter config*/ mochaReporter: { output: 'noFailures' //full, autowatch, minimal } }); };
basePath와 excludes속성, files patter속성, 그리고 preprocessors속성를 수정하라.┌ karma.conf.js ├ package.json ├ webpack.config.js ├ src │ ├ index.js │ └ another_module.js └ tests ├ spec_a.js └ spec_b.js
const myModule = require('./../src/index.js'); describe("Module should return", function () { it("some number", function () { expect(myModule()).toEqual(10); }); });
module.exports = ()=> 10;
karma start로 실행하거나,package.json에 “scripts”: { “test”: “karma start” }를 추가하고, npm test를 실행jasmine문자열로 자스민 프레임워크를 사용한다고 설정했다. 다른 것을 (jasmine, mocha, qunit등) 지원한다.files배열은 브라우저에 포함된 파일과 karma가 보고, 제공하는 파일을 결정합니다.
files: [ // Detailed pattern to include a file. Similarly other options can be used { pattern: 'lib/angular.js', watched: false }, // Prefer to have watched false for library files. No need to watch them for changes // simple pattern to load the needed testfiles // equal to {pattern: 'test/unit/*.spec.js', watched: true, served: true, included: true} 'test/unit/*.spec.js', // this file gets served but will be ignored by the watcher // note if html2js preprocessor is active, reference as `window.__html__['compiled/index.html']` {pattern: 'compiled/index.html', watched: false}, // this file only gets watched and is otherwise ignored {pattern: 'app/index.html', included: false, served: false}, // this file will be served on demand from disk and will be ignored by the watcher {pattern: 'compiled/app.js.map', included: false, served: true, watched: false, nocache: true} ],
생성한 카르마 컴피그 파일로 카르마를 실행하려면 세 가지 카르마 플러그인을 추가 다운로드 해야한다.
karma-jasmine: 카르마에서 자스민을 사용할 수 있다. jasmine-core: karma-jasmine은 카르마가 자스민을 사용할수 있도록 하는 어답터 역할만 한다. 자스민 코드가 있는 jasmine-core를 추가해야 한다. karma-chrome-launcher: 테스트 브라우져로 크롬을 선택했으면 이 플러그인을 설치해서 카르마가 크롬을 사용할 수 있도록 해야한다. 이것도 어답터라고 보면 되겠다.
npm install karma-jasmine jasmine-core karma-chrome-launcher --save-dev
Now that we have gotten the why? out of the way, let’s see how we can go about implementing our own testing framework:
First and foremost, we’ll have to install the libraries that we wish to use to test our systems.
npm install --save-dev mocha chai npm install --save-dev ts-node typescript npm install --save-dev @types/chai @types/mocha
package.json
"scripts": { "test": "mocha --require ts-node/register src/**/*.spec.ts" },
Gulp We need to install two more packages to be able to use Gulp:
npm install gulp gulp-mocha --save-dev
Behavior-Driven JavaScript
function helloWorld(){ return 'Hello world!'; }
describe('Hello world', () => { -- 해설-1 it('says hello', () => { -- 해설-2 expect(helloWorld()) -- 해설-3 .toEqual('Hello world!'); -- 해설-4 }); });
Jasmine은 몇가지 미리만들어진 matcher들을 가지고 있다.
expect(array).toContain(member); expect(fn)toThrow(string); expect(fn).toThrowError(string); expect(instance).toBe(instance); expect(mixed).toBeDefined(); expect(mixed).toBeFalsy(); expect(mixed).toBeNull(); expect(mixed).toBeUndefined(); expect(mixed).toEqual(mixed); expect(mixed).toMatch(pattern); expect(number).toBeCloseTo(number, decimalPlaces); expect(number).toBeGreaterThan(number); expect(number).toBelessThan(number); expect(number).toBeNaN(); expect(spy).toHaveBeenCalled(); expect(spy).toHaveBeenCalledTimes(number); expect(spy).toHaveBeenCalledWith(...arguments);