Using express with Karma to test ember app kit app - ember.js
I've just downloaded and installed ember app kit. I've got it running and am using express to fake a backend by following the included directions.
I've also installed Karma and am attempting to run the tests with it in conjunction with the express backend. I don't believe the express app is being started though because when i view the output of Karma i see it attempting to perform a GET request and failing.
Failed to load resource: the server responded with a status of 404 (Not Found) http://1.10.1.10:9876/api/posts/1
Json is returned when i hit the development port(8000) though.
How do i tell Karma to start up the express app on port 9876 to test against?
I'm using the karma.conf.js from from the ember-app-kit-todos repo
Here is my Gruntfile.js. I also took bits from the todos repo:
module.exports = function(grunt) {
// To support Coffeescript, SASS, LESS and others, just install
// the appropriate grunt package and it will be automatically included
// in the build process:
//
// * for Coffeescript, run `npm install --save-dev grunt-contrib-coffee`
//
// * for SCSS (without SASS), run `npm install --save-dev grunt-sass`
// * for SCSS/SASS support (may be slower), run
// `npm install --save-dev grunt-contrib-sass`
// This depends on the ruby sass gem, which can be installed with
// `gem install sass`
// * for Compass, run `npm install --save-dev grunt-contrib-compass`
// This depends on the ruby compass gem, which can be installed with
// `gem install compass`
// You should not install SASS if you have installed Compass.
//
// * for LESS, run `npm install --save-dev grunt-contrib-less`
//
// * for Stylus/Nib, `npm install --save-dev grunt-contrib-stylus`
//
// * for Emblem, run the following commands:
// `npm uninstall --save-dev grunt-ember-templates`
// `npm install --save-dev grunt-emblem`
// `bower install emblem.js --save`
//
// * For EmberScript, run `npm install --save-dev grunt-ember-script`
//
// * for LiveReload, `npm install --save-dev connect-livereload`
//
// * for displaying the execution time of the grunt tasks,
// `npm install --save-dev time-grunt`
//
// * for minimizing the index.html at the end of the dist task
// `npm install --save-dev grunt-contrib-htmlmin`
//
// * for minimizing images in the dist task
// `npm install --save-dev grunt-contrib-imagemin`
//
// * for using images based CSS sprites (http://youtu.be/xD8DW6IQ6r0)
// `npm install --save-dev grunt-fancy-sprites`
// `bower install --save fancy-sprites-scss`
//
// * for automatically adding CSS vendor prefixes (autoprefixer)
// `npm install --save-dev grunt-autoprefixer`
//
var Helpers = require('./tasks/helpers'),
filterAvailable = Helpers.filterAvailableTasks,
_ = grunt.util._,
path = require('path');
Helpers.pkg = require("./package.json");
if (Helpers.isPackageAvailable("time-grunt")) {
require("time-grunt")(grunt);
}
// Loads task options from `tasks/options/` and `tasks/custom-options`
// and loads tasks defined in `package.json`
var config = _.extend({},
require('load-grunt-config')(grunt, {
configPath: path.join(__dirname, 'tasks/options'),
loadGruntTasks: false,
init: false
}),
require('load-grunt-config')(grunt, { // Custom options have precedence
configPath: path.join(__dirname, 'tasks/custom-options'),
init: false
})
);
grunt.loadTasks('tasks'); // Loads tasks in `tasks/` folder
config.env = process.env;
// App Kit's Main Tasks
// ====================
// Generate the production version
// ------------------
grunt.registerTask('dist', "Build a minified & production-ready version of your app.", [
'clean:dist',
'build:dist',
'copy:assemble',
'createDistVersion'
]);
// Default Task
// ------------------
grunt.registerTask('default', "Build (in debug mode) & test your application.", ['test']);
// Servers
// -------------------
grunt.registerTask('server', "Run your server in development mode, auto-rebuilding when files change.", function(proxyMethod) {
var expressServerTask = 'expressServer:debug';
if (proxyMethod) {
expressServerTask += ':' + proxyMethod;
}
grunt.task.run(['clean:debug',
'build:debug',
expressServerTask,
'watch'
]);
});
grunt.registerTask('server:dist', "Build and preview a minified & production-ready version of your app.", [
'dist',
'expressServer:dist:keepalive'
]);
// Testing
// -------
grunt.registerTask('test', "Run your apps's tests once. Uses Google Chrome by default.", [
'clean:debug', 'build:debug', 'karma:test' ]);
grunt.registerTask('test:ci', "Run your app's tests in PhantomJS. For use in continuous integration (i.e. Travis CI).", [
'clean:debug', 'build:debug', 'karma:ci' ]);
grunt.registerTask('test:browsers', "Run your app's tests in multiple browsers (see tasks/options/testem.js for configuration).", [
'clean:debug', 'build:debug', 'karma:browsers' ]);
grunt.registerTask('test:server', "Start a Karma test server and the standard development server.", function(proxyMethod) {
var expressServerTask = 'expressServer:debug';
if (proxyMethod) {
expressServerTask += ':' + proxyMethod;
}
grunt.task.run(['clean:debug',
'build:debug',
'karma:server',
expressServerTask,
'addKarmaToWatchTask',
'watch'
]);
});
// Worker tasks
// =================================
grunt.registerTask('build:dist', filterAvailable([
'createResultDirectory', // Create directoy beforehand, fixes race condition
'fancySprites:create',
'concurrent:buildDist', // Executed in parallel, see config below
]));
grunt.registerTask('build:debug', filterAvailable([
'jshint:tooling',
'createResultDirectory', // Create directoy beforehand, fixes race condition
'fancySprites:create',
'concurrent:buildDebug', // Executed in parallel, see config below
]));
grunt.registerTask('createDistVersion', filterAvailable([
'useminPrepare', // Configures concat, cssmin and uglify
'concat', // Combines css and javascript files
'cssmin', // Minifies css
'uglify', // Minifies javascript
'imagemin', // Optimizes image compression
// 'svgmin',
'copy:dist', // Copies files not covered by concat and imagemin
'rev', // Appends 8 char hash value to filenames
'usemin', // Replaces file references
'htmlmin:dist' // Removes comments and whitespace
]));
// Parallelize most of the build process
_.merge(config, {
concurrent: {
buildDist: [
"buildTemplates:dist",
"buildScripts",
"buildStyles",
"buildIndexHTML:dist"
],
buildDebug: [
"buildTemplates:debug",
"buildScripts",
"buildStyles",
"buildIndexHTML:debug"
]
}
});
// Templates
grunt.registerTask('buildTemplates:dist', filterAvailable([
'emblem:compile',
'emberTemplates:dist'
]));
grunt.registerTask('buildTemplates:debug', filterAvailable([
'emblem:compile',
'emberTemplates:debug'
]));
// Scripts
grunt.registerTask('buildScripts', filterAvailable([
'jshint:app',
'jshint:tests',
'coffee',
'emberscript',
'copy:javascriptToTmp',
'transpile',
'concat_sourcemap'
]));
// Styles
grunt.registerTask('buildStyles', filterAvailable([
'compass:compile',
'sass:compile',
'less:compile',
'stylus:compile',
'copy:cssToResult',
'autoprefixer:app'
]));
// Index HTML
grunt.registerTask('buildIndexHTML:dist', [
'preprocess:indexHTMLDistApp',
'preprocess:indexHTMLDistTests'
]);
grunt.registerTask('buildIndexHTML:debug', [
'preprocess:indexHTMLDebugApp',
'preprocess:indexHTMLDebugTests'
]);
// Appends `karma:server:run` to every watch target's tasks array
grunt.registerTask('addKarmaToWatchTask', function() {
_.forIn(grunt.config('watch'), function(config, key) {
if (key === 'options') { return; }
config.tasks.push('karma:server:run');
grunt.config('watch.' + key, config);
});
});
grunt.registerTask('createResultDirectory', function() {
grunt.file.mkdir('tmp/result');
});
grunt.initConfig(config);
};
I'm very new to EAK and Karma. Any help would be very much appreciated.
You can configure the location of the proxyURL in the package.json file, as seen here. You'll also need to make sure that the APIMethod is set to 'proxy' instead of 'stub'.
To actually have the server startup on a port other than 8000, you need to set an environment variable at the time you're running the tests. So, if you invoke grunt like this: PORT=9876 grunt test it should start the server on the port you specified.
Related
Emit attempted before Angular Webpack plugin initialization after webpack5 build
I'm using Angular 14 ang webpack version: ^5.58.1. Below is the config: webpack.congif.js const webpackPlugin = require('#ngtools/webpack').AngularWebpackPlugin; module.exports = { mode: 'development', devtool: "source-map", entry: { main: "./js/main.js", mainDrawer: "./js/divdrawer/main.ts", polyfills: "./js/divdrawer/polyfills.ts", entry: "./js/entry.js", thirdpartylibs: "./js/thirdpartylibs.js" }, output: { path: path.join(__dirname, "build/"), filename: "[name]bundle.js" }, module: { rules: [ { parser: { system: true, } } test : /\.(tsx|ts)$/, use: [ { loader: '#ngtools/webpack', options: { configFile: path.resolve('./js/tsconfig.json') }, }, ] }, }, plugins: [ new webpackPlugin({ tsconfig: './js/tsconfig.json', }), new webpack.ContextReplacementPlugin( /\#angular(\\|\/)core(\\|\/)esm5/, path.resolve(__dirname, "./js/divdrawer") ) ] } While generating the build I'm getting below error: ERROR in ./js/divdrawer/filterMappingRemover.ts Module build failed (from ./node_modules/#ngtools/webpack/src/index.js): Error: Emit attempted before Angular Webpack plugin initialization. at D:\MyProject\node_modules\#ngtools\webpack\src\ivy\loader.js:81:18 # ./js/entry.js 10:30-97 ERROR in ./js/divdrawer/main.ts Module build failed (from ./node_modules/#ngtools/webpack/src/index.js): Error: Emit attempted before Angular Webpack plugin initialization. at D:\MyProject\node_modules\#ngtools\webpack\src\ivy\loader.js:81:18 at processTicksAndRejections (internal/process/task_queues.js:95:5) ERROR in ./js/divdrawer/polyfills.ts Module build failed (from ./node_modules/#ngtools/webpack/src/index.js): Error: Emit attempted before Angular Webpack plugin initialization. at D:\MyProject\node_modules\#ngtools\webpack\src\ivy\loader.js:81:18 ERROR in ./js/divdrawer/renderer.ts Module build failed (from ./node_modules/#ngtools/webpack/src/index.js): Error: Emit attempted before Angular Webpack plugin initialization. at D:\MyProject\node_modules\#ngtools\webpack\src\ivy\loader.js:81:18 # ./js/entry.js 9:18-61 All the entries are throwing the errors with above message. As mentioned in webpack config we have multiple entries. This is detected when I upgraded our project to angular 14.(Angular upgrade Steps: v10 --> v11--> v12--> v13/v14) How to configure AngularWebpackPlugin correctly? Is there any alternative way?
For me this solution worked: go to package.json and change your typescript version, If you want to upgrade your angular project to Angular 15 (npm install typescript#"~4.8.0" --save-dev) "devDependencies": { ... "typescript": "~4.8.0" } Angular 14 (npm install typescript#"~4.7.0" --save-dev) "devDependencies": { ... "typescript": "~4.7.0" } Credit to F.R
yes downgrading typescript version to 4.8.2 resolve the issue.
For me, upgrading node version 16.xx to 18.xx (LTS) fixed the issue.
Running Unit and automation UI tests in one place in Jenkins and receive such Error: Failed to launch the browser process
For now we are execute unit tests together with UI automation and for now unit tests is passing OK, but ui automation receive Error: Failed to launch the browser process! for now we have Jenkins file for both tests templates stage('Build npm env and Execute AutomationTests'){ steps { executeDocker(dockerImage: 'docker.wdf.sap.corp:50000/buildkite/puppeteer:latest', dockerWorkspace: '/home/piper'){ sh 'npm install' sh 'npm update -g' sh 'npx browserslist#latest --update-db' } } } stage('Update Build Badge'){ steps { script { def userIdCause = currentBuild.getBuildCauses('hudson.model.Cause$UserIdCause') def userId = userIdCause[0].userId gitCommit = sh(returnStdout: true, script: 'git rev-parse --short=8 HEAD').trim() manager.addShortText('User: ' + userId + ' , Commit Sha: ' + gitCommit , "grey", "transparent", "0px", "white") } } } stage('Build UI Application and Execute UnitTests'){ steps { executeDocker(dockerImage: 'node:14-stretch', dockerWorkspace: '/home/piper'){ sh 'npm install' sh 'npm run build-dev' sh 'npm run test' stash name: "build", includes: 'dist/**, coverage/**' } } } also we have separate config files this one for unit tests module.exports = { preset: "#vue/cli-plugin-unit-jest", collectCoverage: true, collectCoverageFrom: [ "src/**/*.{js,vue}", "!src/main.js", // No need to cover bootstrap file ], } and this is config file for ui automation module.exports = { preset: "#vue/cli-plugin-unit-jest", collectCoverage: true, collectCoverageFrom: [ "src/**/*.{js,vue}", "!src/main.js", // No need to cover bootstrap file ], } and setup file for ui automation import puppeteer from "puppeteer" jest.setTimeout(60000) beforeAll(async () => { global.browser = await puppeteer.launch({ headless: true, slowMo: 0, args: ["--disable-setuid-sandbox", "--no-sandbox"], }) }) afterAll(() => { global.browser.close() })
Unit testing in vuejs
I am trying to configure/run my first unit test for Vuejs. But I can't get past the configuration issues. I have tried installing the libraries but for some reason I keep getting errors. Here is what an example of my code looks like: My directory structure: hello/ dist/ node_modules/ src/ components/ hello.vue test/ setup.js test.spec.js .babelrc package.json webpack.config.js Contents inside my files src/components/hello.vue <template> <div> {{message}} </div> </template> <script> export default { name: 'hello', data () { return message: 'Hi' }, created () { // ... } } test/setup.js // setup JSDOM require('jsdom-global')() // make expect available globally global.expect = require('expect') test/test.spect.js import { shallow } from 'vue/test-utils' import { hello} from '../../../src/components/hello.vue' describe('hello', () => { // just testing simple data to see if it works expect(1).toBe(1) }) .babelrc { "env": { "development": { "presets": [ [ "env", { "modules": false } ] ] }, "test": { "presets": [ [ "env", { "modules": false, "targets": { "node": "current" } } ] ], "plugins": [ "istanbul" ] } } } package.json ... "scripts": { "build": "webpack -p", "test": "cross-env NODE_ENV=test nyc mocha-webpack --webpack-config webpack.config.js --require test/setup.js test/**/*.spec.js" }, "devDependencies": { "babel-core": "^6.26.0", "babel-loader": "^7.1.2", "babel-preset-env": "^1.6.1", "cross-env": "^5.1.1", "css-loader": "^0.28.7", "file-loader": "^1.1.5", "node-sass": "^4.7.2", "sass-loader": "^6.0.6", "vue-loader": "^13.5.0", "vue-template-compiler": "^2.5.9", "webpack": "^3.10.0", "webpack-dev-server": "^2.9.7", "jsdom": "^11.3.0", "jsdom-global": "^3.0.2", "mocha": "^3.5.3", "mocha-webpack": "^1.0.0-rc.1", "nyc": "^11.4.1", "expect": "^21.2.1", "#vue/test-utils": "^1.0.0-beta.12" }, ... "nyc": { "include": [ "src/**/*.(js|vue)" ], "instrument": false, "sourceMap": false } and finally my webpack.config.js ... if(process.env.NODE_ENV == "test") { module.exports.externals = [ require ('webpack-node-externals')()] module.exports.devtool = 'inline-cheap-module-source-map' } now when I run npm test from my root folder hello/ I get this error: > hello#1.0.0 test C:\Users\john\vue-learn\hello > npm run e2e > hello#1.0.0 e2e C:\Users\john\vue-learn\hello > node test/e2e/runner.js Starting selenium server... started - PID: 12212 [Test] Test Suite ===================== Running: default e2e tests × Timed out while waiting for element <#app> to be present for 5000 milliseconds. - expected "visible" but got: "not found" at Object.defaultE2eTests [as default e2e tests] (C:/Users/john/Google Drive/lab/hello/test/e2e/specs/test.js:13:8) at _combinedTickCallback (internal/process/next_tick.js:131:7) FAILED: 1 assertions failed (20.281s) _________________________________________________ TEST FAILURE: 1 assertions failed, 0 passed. (20.456s) × test - default e2e tests (20.281s) Timed out while waiting for element <#app> to be present for 5000 milliseconds. - expected "visible" but got: "not found" at Object.defaultE2eTests [as default e2e tests] (C:/Users/john/Google Drive/lab/hello/test/e2e/specs/test.js:13:8) at _combinedTickCallback (internal/process/next_tick.js:131:7) npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! hello#1.0.0 e2e: `node test/e2e/runner.js` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the hello#1.0.0 e2e script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\john\AppData\Roaming\npm-cache\_logs\2018-04-03T23_53_15_976Z-debug.log npm ERR! Test failed. See above for more details. I don't know why this happens. When I installed my webpack project at first I didn't install a testing library with the npm init command so there are no conflicts, but still I get that error: update (after bounty) I'm just trying to test my vuejs application. Hopefully with jasmine/karma. If anyone knows how to integrate these into a simple app and run the firsts test, I can take it from there. My problem is not writing tests but configuring it
So first thing you didn't need to enable the end to end testing in your project. I would say start fresh $ npm install -g vue-cli $ vue init webpack vue-testing ? Project name vue-testing ? Project description A Vue.js project ? Author Tarun Lalwani <tarun.lalwani#payu.in> ? Vue build standalone ? Install vue-router? Yes ? Use ESLint to lint your code? Yes ? Pick an ESLint preset Standard ? Set up unit tests Yes ? Pick a test runner karma ? Setup e2e tests with Nightwatch? No ? Should we run `npm install` for you after the project has been created? (recommended) yarn Say N to Setup e2e tests with Nightwatch and use Karma for the Pick a test runner. $ npm test > vue-testing#1.0.0 test /Users/tarun.lalwani/Desktop/tarunlalwani.com/tarunlalwani/workshop/ub16/so/vue-testing > npm run unit > vue-testing#1.0.0 unit /Users/tarun.lalwani/Desktop/tarunlalwani.com/tarunlalwani/workshop/ub16/so/vue-testing > cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run 07 04 2018 21:35:28.620:INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:9876/ 07 04 2018 21:35:28.629:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency 07 04 2018 21:35:28.645:INFO [launcher]: Starting browser PhantomJS 07 04 2018 21:35:32.891:INFO [PhantomJS 2.1.1 (Mac OS X 0.0.0)]: Connected on socket M1HeZIiOis3eE3mLAAAA with id 44927405 HelloWorld.vue ✓ should render correct contents PhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 1 of 1 SUCCESS (0.061 secs / 0.041 secs) TOTAL: 1 SUCCESS =============================== Coverage summary =============================== Statements : 100% ( 2/2 ) Branches : 100% ( 0/0 ) Functions : 100% ( 0/0 ) Lines : 100% ( 2/2 ) ================================================================================ Now your npm test would work fine.
According to the error logs you provide here, the failing tests that you spot are the End to End ones. Indeed, by executing the command npm test e2e you're testing using Nightwatch. See under /tests/e2e/specs. Here you should have a default test file checking that your Vue application properly create a DOM element identified as app. The test should be the following: // For authoring Nightwatch tests, see // http://nightwatchjs.org/guide#usage module.exports = { 'default e2e tests': function (browser) { // automatically uses dev Server port from /config.index.js // default: http://localhost:8080 // see nightwatch.conf.js const devServer = browser.globals.devServerURL browser .url(devServer) .waitForElementVisible('#app', 5000) .assert.elementPresent('.hello') .assert.containsText('h1', 'Welcome to Your Vue.js App') .assert.elementCount('img', 1) .end() } } In your case this test is failing because you have probably removed the file named App.vue that is generated through vue-cli scaffolding. The error you get is because the above test checks, with a 5 seconds timeout, if a DOM node named "app" is rendered (i.e.: .waitForElementVisible('#app', 5000)). Basically it is failing because you actually do not provide this div in your application anymore (due of App.vue removal, maybe). So you have two options here: restoring the App.vue file (i.e.: create a div identified as 'app' where you mount a Vue instance); editing the end to end according to your needs. Hope this helps!
Test ES6 modules with Jest [duplicate]
This question already has answers here: Does Jest support ES6 import/export? (10 answers) Closed 11 months ago. How to test ES6 modules with Jest. Example: sum.js const sum = function (a, b) { return a + b; } export default sum; sum.test.js import sum from './sum'; test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(3); });
The only requirement is to config your test environment to Babel, and add the es2015 transform plugin: Step 1: Add your test environment to .babelrc in the root of your project: { "env": { "test": { "plugins": ["#babel/plugin-transform-modules-commonjs"] } } } Step 2: Install the es2015 transform plugin: npm install --save-dev #babel/plugin-transform-modules-commonjs And that's it. Jest will enable compilation from ES modules to CommonJS automatically, without having to inform additional options to your jest property inside package.json.
The solutions above didn't work for me. I was able to solve with this: yarn add --dev babel-jest #babel/core #babel/preset-env #babel/preset-typescript babel.config.js module.exports = { presets: [ [ '#babel/preset-env', { targets: { node: 'current', }, }, ], '#babel/preset-typescript' ], }; where I'm using typescript. Reference.
Verbose output in jest js
is any option for verbore output for testing by jest? I can see which modules are mocked. I tried jasmine.VERBOSE = true; but not working. Thanks for answer.
To get verbose mode in Jest, you can run Jest with the --verbose tag. In your packages.json, you can write: "scripts": { "test": "jest --verbose" }, Then you can run npm test Alternatively, if you are using gulp-jest, to get Jest in verbose mode, find the index.js file of the gulp-jest folder in node_modules and add a verbose: true to the jest.runCLI block. jest.runCLI({ config: options, verbose: true }
simple add in package.json { ... ... "jest": { "verbose": true }, ... ... }
Create jest.config.js file in root directory and add this to the module export module.exports = { // some code here.. verbose: true, // some code here... }