I recently started the move from a custom gulp script that used to take care of all sorts of stuff to webpack. I have it working to a point where transpiling, bundling and serving the client app in the browser works great.
Now, when I was using gulp to run my karma tests against the bundled app.js file, the gulp script would first bundle the app.js file and then spit it into the dist folder. This file would then be used by karma to run the tests against it. My gulp test task would also watch for any test file changes or for the bundle file change, and re-run the tests based on that.
With webpack, I understand this dist/app.js resides in-memory, rather than being written to the disk (at least that's how I set it up). The problem with that is that it seems that my bundled app (which gets served fine with webpack-dev-server --open
) does not get loaded by karma for some reason and I can't figure out what the missing piece of the puzzle is.
This is how my folder structure looks like (I left just the most basic stuff that could be relevant to the issue):
package.json
webpack.config.js
karma.conf.js
src/
--app/
----[other files/subfolders]
----app.ts
----index.ts
--boot.ts
--index.html
tests/
--common/
----services/
------account.service.spec.js
This is my webpack.config.js
var path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const ForkTsCheckerWebpackPlugin = require("fork-ts-checker-webpack-plugin");
module.exports = {
context: path.join(__dirname),
entry: "./src/boot.ts",
plugins: [
new webpack.HotModuleReplacementPlugin(),
new ForkTsCheckerWebpackPlugin(),
new CleanWebpackPlugin(["dist"]),
new HtmlWebpackPlugin({
template: "./src/index.html"
})
],
module: {
rules: [
{
test: /\.scss$/,
use: [{
loader: "style-loader"
}, {
loader: "css-loader"
}, {
loader: "sass-loader"
}]
},
{
test: /\.tsx?$/,
use: [{
loader: "ts-loader",
options: {
transpileOnly: true,
exclude: /node_modules/
}
}]
},
{
test: /\.html$/,
loaders: "html-loader",
options: {
attrs: [":data-src"],
minimize: true
}
}
]
},
resolve: {
extensions: [".tsx", ".ts", ".js"],
alias: {
"common": path.resolve(__dirname, "src/app/common"),
"common/*": path.resolve(__dirname, "src/app/common/*"),
"modules": path.resolve(__dirname, "src/app/modules"),
"modules/*": path.resolve(__dirname, "src/app/modules/*"),
}
},
output: {
filename: "app.js",
path: path.resolve(__dirname, "dist")
},
devtool: "inline-source-map",
devServer: {
historyApiFallback: true,
hot: false,
contentBase: path.resolve(__dirname, "dist")
}
};
This is my karma.conf.js
const webpackConfig = require("./webpack.config");
module.exports = function (config) {
config.set({
frameworks: ["jasmine"],
files: [
"node_modules/angular/angular.js",
"node_modules/angular-mocks/angular-mocks.js",
"dist/app.js", // not sure about this
"tests/common/*.spec.js",
"tests/common/**/*.spec.js"
],
preprocessors: {
"dist/app.js": ["webpack", "sourcemap"], // not sure about this either
"tests/common/*.spec.js": ["webpack", "sourcemap"],
"tests/common/**/*.spec.js": ["webpack", "sourcemap"]
},
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true,
stats: {
chunks: false
}
},
reporters: ["progress", "coverage"], // , "teamcity"],
coverageReporter: {
dir: "coverage",
reporters: [
{ type: "html", subdir: "html" },
{ type: "text-summary" }
]
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: [
"PhantomJS"
//"Chrome"
],
singleRun: false,
concurrency: Infinity,
browserNoActivityTimeout: 100000
});
};
This is the boot.ts which is basically the entry point to the app:
import * as app from "./app/app";
import "./styles/app.scss";
// This never gets written to the console
// so I know it never gets loaded by karma
console.log("I NEVER OUTPUT TO CONSOLE");
This is the app.ts (which then references anything below it:
import * as ng from "angular";
import * as _ from "lodash";
import "@uirouter/angularjs";
import "angular-cookies";
import "angular-material"
import "angular-local-storage";
import "angular-sanitize";
import "angular-messages";
import "angular-file-saver";
import "angular-loading-bar";
import "satellizer";
export * from "./index";
import * as Module from "common/module";
import * as AuthModule from "modules/auth/module";
import * as UserModule from "modules/user/module";
import { MyAppConfig } from "./app.config";
import { MyAppRun } from "./app.run";
export default ng.module("MyApp", [
"ngCookies",
"ngSanitize",
"ngMessages",
"ngFileSaver",
"LocalStorageModule",
"ui.router",
"ngMaterial",
"satellizer",
"angular-loading-bar",
Module.name,
AuthModule.name,
UserModule.name
])
.config(MyAppConfig)
.run(MyAppRun);
And finally, this is the account.service.spec.js
describe("Account service", function () {
// SETUP
var _AccountService;
beforeEach(angular.mock.module("MyApp.Common"));
beforeEach(angular.mock.inject(function (_AccountService_) {
// CODE NEVER GETS IN HERE EITHER
console.log("I NEVER OUTPUT TO CONSOLE");
_AccountService = _AccountService_;
}));
function expectValidPassword(result) {
expect(result).toEqual({
minCharacters: true,
lowercase: true,
uppercase: true,
digits: true,
isValid: true
});
}
// TESTS
describe(".validatePassword()", function () {
describe("on valid password", function () {
it("returns valid true state", function () {
expectValidPassword(_AccountService.validatePassword("asdfASDF123"));
expectValidPassword(_AccountService.validatePassword("as#dfAS!DF123%"));
expectValidPassword(_AccountService.validatePassword("aA1234%$2"));
expectValidPassword(_AccountService.validatePassword("YYyy22!@"));
expectValidPassword(_AccountService.validatePassword("Ma#38Hr$"));
expectValidPassword(_AccountService.validatePassword("aA1\"#$%(#/$\"#$/(=/#$=!\")(\")("));
})
});
});
});
And this is the output of running the karma start
> npm test
> [email protected] test E:\projects\Whatever
> karma start
clean-webpack-plugin: E:\projects\Whatever\dist has been removed.
Starting type checking service...
Using 1 worker with 2048MB memory limit
31 10 2017 21:47:23.372:WARN [watcher]: Pattern "E:/projects/Whatever/dist/app.js" does not match any file.
31 10 2017 21:47:23.376:WARN [watcher]: Pattern "E:/projects/Whatever/tests/common/*.spec.js" does not match any file.
ts-loader: Using [email protected] and E:\projects\Whatever\tsconfig.json
No type errors found
Version: typescript 2.4.2
Time: 2468ms
31 10 2017 21:47:31.991:WARN [karma]: No captured browser, open http://localhost:9876/
31 10 2017 21:47:32.004:INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:9876/
31 10 2017 21:47:32.004:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
31 10 2017 21:47:32.010:INFO [launcher]: Starting browser PhantomJS
31 10 2017 21:47:35.142:INFO [PhantomJS 2.1.1 (Windows 8 0.0.0)]: Connected on socket PT-pno0eF3hlcdNEAAAA with id 71358105
PhantomJS 2.1.1 (Windows 8 0.0.0) Account service .validatePassword() on valid password returns valid true state FAILED
forEach@node_modules/angular/angular.js:410:24
loadModules@node_modules/angular/angular.js:4917:12
createInjector@node_modules/angular/angular.js:4839:30
WorkFn@node_modules/angular-mocks/angular-mocks.js:3172:60
loaded@http://localhost:9876/context.js:162:17
node_modules/angular/angular.js:4958:53
TypeError: undefined is not an object (evaluating '_AccountService.validatePassword') in tests/common/services/account.service.spec.js (line 742)
webpack:///tests/common/services/account.service.spec.js:27:0 <- tests/common/services/account.service.spec.js:742:44
loaded@http://localhost:9876/context.js:162:17
PhantomJS 2.1.1 (Windows 8 0.0.0) Account service .validatePassword() on valid amount of characters returns minCharacters true FAILED
forEach@node_modules/angular/angular.js:410:24
loadModules@node_modules/angular/angular.js:4917:12
createInjector@node_modules/angular/angular.js:4839:30
WorkFn@node_modules/angular-mocks/angular-mocks.js:3172:60
node_modules/angular/angular.js:4958:53
TypeError: undefined is not an object (evaluating '_AccountService.validatePassword') in tests/common/services/account.service.spec.js (line 753)
webpack:///tests/common/services/account.service.spec.js:38:0 <- tests/common/services/account.service.spec.js:753:37
PhantomJS 2.1.1 (Windows 8 0.0.0): Executed 2 of 2 (2 FAILED) ERROR (0.017 secs / 0.015 secs)
Please note the few places where I left console.logs which never get triggered. That's how I know the app doesn't get loaded. That and the fact that jasmine is not able to inject the service I want to test.
I'm using:
karma v1.7.1
karma-webpack v2.0.5
webpack v3.3.0
Any ideas? What am I doing wrong? I'm under the impression that my webpack.config.js is supposed to bundle my AngularJS/TS app and then essentially feed it to karma, but for whatever reason, that doesn't seem to work. Or do I have some fundamental misconception of how this is supposed to work?
Thank you.
I extracted a few files into a simple app and put it to github so the issue could be easily reproduced.
npm install # install deps
npm run serve:dev # run the app - works
npm run test # run karma tests - doesn't work
Edit:
I managed to make the tests run by replacing the:
"dist/app.js"
in karma setup with
"src/boot.ts"
but that wouldn't drill down or load/import the rest of the app. Then I tried importing only the class I want to test to the spec but then I couldn't mock any DI-injected services that the class I'm testing is using. Anyway, I pretty much gave up on this at this stage and stopped trying to figure out how to do this, moving to ang2+.
I faced a similar issue during transferring my AngularJS project building from Grunt to Webpack and tried 2 different approaches.
1. Webpack and Karma as two separate processes. I made an npm-script running webpack
and karma
in parallel. It looked like
"dev-build": "webpack --config webpack/development.js",
"dev-test": "karma start test/karma.development.conf.js",
"test": "concurrently --kill-others --raw \"npm run dev-build\" \"npm run dev-test\""
Instead of concurrently
you may do anything else, npm-run-all
or even &
. In that configuration Karma did not have any Webpack stuff, she just watched the ./temp folder for built distributive and worked stand-alone, re-running herself each time the tests or distributive had been changed. Webpack was started in the dev-mode (via "dev-build" script), he watched the ./src folder and compiled distributive into the ./temp folder. When he updated ./temp, Karma started tests re-running.
It worked, despite the problems of first Karma fail. Karma started tests before the Webpack first compilation had been finished. It's not critical. Also, a playing with restartOnFileChange
setting could help... Maybe there is another good workaround. I didn't finished this story, I switched to option 2, which I believe fits the Webpack-way a bit more than just described one.
2. Karma is the only process, which uses Webpack. I refused the ./temp folder and decided that for the dev-mode all operations should be in-memory. Dev-mode Webpack got following settings (./webpack/development.js):
entry: { 'ui-scroll': path.resolve(__dirname, '../src/ui-scroll.js') },
output: { filename: '[name].js' }, // + path to ./dist in prod
devtool: 'inline-source-map', // 'source-map' in prod
compressing: false,
watch: true
Dev-mode Karma (./test/karma.development.conf.js):
files: [
// external libs
// tests specs
'../src/ui-scroll.js' // ../dist in prod
],
preprocessors: { // no preprocessors in prod
'../src/ui-scroll.js': ['webpack', 'sourcemap']
},
webpack: require('../webpack/development.js'), // no webpack in prod
autoWatch: true,
keepalive: true,
singleRun: false
This also required two npm packages to be installed: karma-webpack
and karma-sourcemap-loader
. The first option looks more familiar after Grunt/gulp, but this one is simpler, shorter and more stable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With