Unit testing in vuejs - unit-testing

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!

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.

Using a (Zustand) function mock with Jest results in "TypeError: create is not a function"

I'm following the Zustand wiki to implement testing, but the provided solution is not working for a basic test for app rendering. My project is built on top of the Electron React Boilerplate boilerplate project.
Here's the full error. Jest is using node with experimental-vm-modules because I followed the the Jest docs to support ESM modules.
$ cross-env NODE_OPTIONS=--experimental-vm-modules jest
(node:85003) ExperimentalWarning: VM Modules is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
jest-haste-map: Haste module naming collision: myproject
The following files share their name; please adjust your hasteImpl:
* <rootDir>/package.json
* <rootDir>/src/package.json
FAIL src/__tests__/App.test.tsx
● Test suite failed to run
TypeError: create is not a function
12 | }
13 |
> 14 | const useNotifs = create<NotifsState>(
| ^
15 | // devtools(
16 | (set) => ({
17 | notifStore: notifsDefault.notifStore,
at src/state/notifs.ts:14:19
at TestScheduler.scheduleTests (node_modules/#jest/core/build/TestScheduler.js:333:13)
at runJest (node_modules/#jest/core/build/runJest.js:387:19)
at _run10000 (node_modules/#jest/core/build/cli/index.js:408:7)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 11.882 s
Ran all test suites.
error Command failed with exit code 1.
At the top of the notifs.ts file, Zustand is imported normally with import create from 'zustand'.
Jest config in package.json:
...
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/config/mocks/fileMock.js",
"\\.(css|less|sass|scss)$": "identity-obj-proxy",
"zustand": "<rootDir>/src/__mocks__/zustand.js",
},
"transformIgnorePatterns": [
"node_modules/(?!(zustand)/)",
"<rootDir>/src/node_modules/"
],
"moduleDirectories": [
"node_modules",
"src/node_modules"
],
"moduleFileExtensions": [
"js",
"jsx",
"ts",
"tsx",
"json"
],
"moduleDirectories": [
"node_modules",
"src/node_modules"
],
"extensionsToTreatAsEsm": [
".ts",
".tsx"
],
...
I have left the ./src/__mocks__/zustand.js file exactly the same as from the Zustand wiki Testing page. I receive the same error whether or not I have zustand in the transformIgnorePatterns.
My Babel configuration includes [require('#babel/plugin-proposal-class-properties'), { loose: true }], in the plugins section, and output.library.type is 'commonjs2'
My tsconfig.json has compilerOptions.module set to "CommonJS", and the project's package.json "type" field is set to "commonjs".
Dependency versions:
"#babel/core": "^7.12.9",
"#babel/preset-env": "^7.12.7",
"#babel/preset-react": "^7.12.7",
"#babel/preset-typescript": "^7.12.7",
"#babel/register": "^7.12.1",
"#babel/plugin-proposal-class-properties": "^7.12.1",
"#testing-library/jest-dom": "^5.11.6",
"#testing-library/react": "^11.2.2",
"babel-jest": "^27.0.6",
"babel-loader": "^8.2.2",
"jest": "^27.0.6",
"regenerator-runtime": "^0.13.9",
"source-map-support": "^0.5.19",
"typescript": "^4.0.5",
"webpack": "^5.5.1",
"zustand": "^3.5.5"
I don't know what else could be relevant, just let me know if anything else is needed. Any and all help appreciated, thanks for your time.
To do this you should use the actual store of your app
const initialStoreState = useStore.getState()
beforeEach(() => {
useStore.setState(initialStoreState, true)
})
useStore.setState({ me: memberMockData, isAdmin: true })
The documentation seems off. So don't follow it.
use jest 28.0.0-alpha.0 will simply resolve the issue.
I think the problem is zustand uses '.mjs' as the entry point.

How to run Rails System tests in Heroku CI

How do I configure Heroku CI to run System tests?
This is my app.json, where I included what I thought would be the necessary buildpacks:
{
"environments": {
"test": {
"scripts": {
"test-setup": "bin/rails assets:precompile",
"test": "bin/rails test:system"
},
"addons":[
"heroku-postgresql:in-dyno"
],
"buildpacks": [
{ "url": "https://github.com/heroku/heroku-buildpack-google-chrome" },
{ "url": "heroku/nodejs" },
{ "url": "heroku/ruby"}
]
}
}
}
But when I deploy, I get the following error:
-----> Running test command `bin/rails test:system`...
rails aborted!
Webdrivers::BrowserNotFound: Failed to find Chrome binary.
I suspect I am missing something very basic....
I running Rails 6.0.1 and Ruby 2.6.3.
Did you setup your webdriver correctly to find the correct binary as mentioned on the official UAT wiki page of heroku?
Add gem 'webdrivers' to your Gemfile.
Add the following code snippet to your test_helper.rb (as stated on heroku buildback wiki and on webdrivers wiki):
require 'webdrivers' # Make sure webdrivers are loaded.
chrome_bin = ENV['GOOGLE_CHROME_SHIM'] if ENV['GOOGLE_CHROME_SHIM'].present?
chrome_capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(
chromeOptions: {
# You may want to use a different args
args: %w[headless disable-gpu window-size=1400x1400],
binary: chrome_bin
}
)
Capybara.register_driver :heroku_chrome do |app|
Capybara::Selenium::Driver.new(app, browser: :chrome, desired_capabilities: chrome_capabilities)
end
Afterwards tell your system test to use your custom chrome driver by adding it to your application_system_test_case.rb.
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
driven_by :heroku_chrome
end

Gulp unhandled error 182

I have a django blog project, and am trying to use bower to manage my packages.
When running 'gulp' from my console, I get the following error :
(py3) ➜ nomadpad git:(master) ✗ gulp
[15:16:15] Using gulpfile ~/code/nomadpad/gulpfile.js
[15:16:15] Starting 'css'...
[15:16:16] Finished 'css' after 1.23 s
[15:16:16] Starting 'html'...
[15:16:16] Finished 'html' after 3.38 ms
[15:16:16] Starting 'scripts'...
[15:16:16] Finished 'scripts' after 4.43 ms
[15:16:16] Starting 'default'...
[15:16:16] Finished 'default' after 38 μs
events.js:182
throw er; // Unhandled 'error' event
^
CssSyntaxError: /Users/davidmellor/code/nomadpad/bower_components/jquery/dist/jquery.js:756:9: Unknown word
at Input.error (/Users/davidmellor/code/nomadpad/node_modules/postcss/lib/input.js:119:22)
at Parser.unknownWord (/Users/davidmellor/code/nomadpad/node_modules/postcss/lib/parser.js:506:26)
at Parser.other (/Users/davidmellor/code/nomadpad/node_modules/postcss/lib/parser.js:171:18)
at Parser.parse (/Users/davidmellor/code/nomadpad/node_modules/postcss/lib/parser.js:84:26)
at parse (/Users/davidmellor/code/nomadpad/node_modules/postcss/lib/parse.js:24:16)
at new LazyResult (/Users/davidmellor/code/nomadpad/node_modules/postcss/lib/lazy-result.js:70:24)
at Processor.process (/Users/davidmellor/code/nomadpad/node_modules/postcss/lib/processor.js:117:12)
at /Users/davidmellor/code/nomadpad/node_modules/gulp-postcss/index.js:51:12
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:169:7)
My bower.json in the root folder looks like this :
{
"name": "blog_postcssgulp",
"description": "",
"main": "gulpfile.js",
"authors": [
"DMells <dave#davemellor.com>"
],
"license": "ISC",
"homepage": "https://github.com/DMells/nomadpad",
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
],
"dependencies": {
"jquery": "^3.3.1",
"modernizr": "^3.5.0"
}
}
I'm not sure what to do here, please can anyone assist?
Many thanks
If anyone else comes across this, I found the solution by removing my bower_components folder and then reinstalling bower, as well as the jquery package.
npm install bower --save-dev
And then the jquery package:
bower install jquery --save-dev

beforeEach fails in karma + Mocha with angular 4 upgrade

Context
I have confirmed "green" builds on the master branch which is using angular-cli 1.0.0 and the old angular2 dependencies. My Objective is to upgrade from angular2 to angular4.
Post upgrade issue
The application works
The unit tests fail in karma using ng test and npm run test which are equivalent
Working configuration
specifically the package.json is as follows.
...
"dependencies": {
"#angular/common": "^2.4.0",
"#angular/compiler": "^2.4.0",
"#angular/core": "^2.4.0",
"#angular/forms": "^2.4.0",
"#angular/http": "^2.4.0",
"#angular/platform-browser": "^2.4.0",
"#angular/platform-browser-dynamic": "^2.4.0",
"#angular/router": "^3.4.0",
...
},
"devDependencies": {
"#angular/cli": "1.0.0",
"#angular/compiler-cli": "^2.4.0",
...
}
With the following test result
Chromium 53.0.2785 (Ubuntu 0.0.0): Executed 82 of 83 (skipped 1) SUCCESS (5.674 secs / 0.061 secs)
Angular 4 upgrade fails the tests
When I try to upgrade the angular4 dependencies with a very specific diff the application runs successfully, however I get failed/repeated tests for the upgrade like so Chromium 53.0.2785 (Ubuntu 0.0.0): Executed 127 of 83 (32 FAILED) (skipped 2) (7.521 secs / 0.101 secs)
What I find fascinating about the result is that there are 44 tests run in addition to the number of tests I actually have. It also appears that the only tests that fail are the duplicate tests that are running and they fail directly after they succeed. On investigation is seems that these tests would fail if their before each were not run
Chrome 56.0.2924 (Linux 0.0.0): Executed 67 of 83 (13 FAILED) (0 secs / 0.11 secs)
✔ will raise a houseCreated event
Chrome 56.0.2924 (Linux 0.0.0) HouseListComponent when valid input is provided (while in create mode) will raise a houseCreated event FAILED
AssertionError: expected { Object (country, state, ...) } to equal { Object (country, state, ...) }
at Context.<anonymous> (webpack:///src/app/housing/components/edit/house-edit.component.spec.ts:69:40 <- src/test.ts:26683:54)
at ZoneDelegate.invoke (webpack:///~/zone.js/dist/zone.js:365:0 <- src/polyfills.ts:1520:26)
at ProxyZoneSpec.Array.concat.ProxyZoneSpec.onInvoke (webpack:///~/zone.js/dist/proxy.js:79:0 <- src/test.ts:88673:39)
at ZoneDelegate.invoke (webpack:///~/zone.js/dist/zone.js:364:0 <- src/polyfills.ts:1519:32)
at Zone.run (webpack:///~/zone.js/dist/zone.js:125:0 <- src/polyfills.ts:1280:43)
at Context.<anonymous> (webpack:///~/zone.js/dist/mocha-patch.js:88:0 <- src/test.ts:88521:33)
at webpack:///~/zone.js/dist/mocha-patch.js:140:0 <- src/test.ts:88573:33
at ZoneDelegate.invokeTask (webpack:///~/zone.js/dist/zone.js:398:0 <- src/polyfills.ts:1553:31)
at Zone.runTask (webpack:///~/zone.js/dist/zone.js:165:0 <- src/polyfills.ts:1320:47)
at drainMicroTaskQueue (webpack:///~/zone.js/dist/zone.js:593:0 <- src/polyfills.ts:1748:35)
at ZoneTask.invoke (webpack:///~/zone.js/dist/zone.js:464:0 <- src/polyfills.ts:1619:25)
at timer (webpack:///~/zone.js/dist/zone.js:1540:0 <- src/polyfills.ts:2695:29)
Chrome 56.0.2924 (Linux 0.0.0): Executed 68 of 83 (14 FAILED) (0 secs / 0.111 secs)
✖ will raise a houseCreated event
broken configuration
...
"dependencies": {
"#angular/common": "^4.0.1",
"#angular/compiler": "^4.0.1",
"#angular/core": "^4.0.1",
"#angular/forms": "^4.0.1",
"#angular/http": "^4.0.1",
"#angular/platform-browser": "^4.0.1",
"#angular/platform-browser-dynamic": "^4.0.1",
"#angular/router": "^4.0.1",
...
},
"devDependencies": {
"#angular/cli": "1.0.0",
"#angular/compiler-cli": "^4.0.1",
...
}
Same tests on a different runner
In attempt to identify if the issue was the tests or the runner, I ran the exact same tests with the wallabyjs runner and I get No failing tests, 82 passing which is perfectly inline with master using the upgraded angular4 dependencies. This would seem to indicate that the issues is specific to karma and not the tests.
resources
Working master
Broken branch
Errors
There are a number of test errors, however they all seem to be related to beforeEach. The test module should not already be instantiated which seems to be a weird side effect from the repeating tests.
Chrome 56.0.2924 (Linux 0.0.0) car reducer "before each" hook for "will return array removes existing values when state is not empty" FAILED
Error: Cannot configure the test module when the test module has already been instantiated. Make sure you are not using `inject` before `TestBed.configureTestingModule`.
at TestBed.Array.concat.TestBed._assertNotInstantiated (webpack:///~/#angular/core/#angular/core/testing.es5.js:749:0 <- src/test.ts:25844:19) [ProxyZone]
at TestBed.Array.concat.TestBed.configureTestingModule (webpack:///~/#angular/core/#angular/core/testing.es5.js:671:0 <- src/test.ts:25766:14) [ProxyZone]
at Function.Array.concat.TestBed.configureTestingModule (webpack:///~/#angular/core/#angular/core/testing.es5.js:576:0 <- src/test.ts:25671:22) [ProxyZone]
at Context.<anonymous> (webpack:///src/app/car/reducers/car.reducer.spec.ts:30:12 <- src/test.ts:31440:27) [ProxyZone]
at ProxyZoneSpec.Array.concat.ProxyZoneSpec.onInvoke (webpack:///~/zone.js/dist/proxy.js:79:0 <- src/test.ts:88673:39) [ProxyZone]
at Zone.run (webpack:///~/zone.js/dist/zone.js:125:0 <- src/polyfills.ts:1280:43) [<root> => ProxyZone]
at Context.<anonymous> (webpack:///~/zone.js/dist/mocha-patch.js:88:0 <- src/test.ts:88521:33) [<root>]
Then after the before each fails then we get more errors regarding the property call
Chrome 56.0.2924 (Linux 0.0.0) car reducer "before each" hook for "will return array removes existing values when state is not empty" FAILED
TypeError: Cannot read property 'call' of undefined
at ZoneDelegate.invokeTask (webpack:///~/zone.js/dist/zone.js:398:0 <- src/polyfills.ts:1553:31)
at Zone.runTask (webpack:///~/zone.js/dist/zone.js:165:0 <- src/polyfills.ts:1320:47)
at ZoneTask.invoke (webpack:///~/zone.js/dist/zone.js:460:0 <- src/polyfills.ts:1615:38)
at timer (webpack:///~/zone.js/dist/zone.js:1540:0 <- src/polyfills.ts:2695:29)
Chrome 56.0.2924 (Linux 0.0.0): Executed 45 of 83 (8 FAILED) (0 secs / 0.092 secs)
Multiple references in the frameworks array should be avoided with Karma. Use the plugins instead
This issue around the failing beforeEach was actually a red herring and a side effect of the repeating tests. It appears that the life cycle being executed was:
beforeEach
it('myTest1') pass
it('myTest1') fail
beforeEach
it('myTest2') pass
it('myTest2') fail
If we stop the tests repeating then the beforeEach issue doesn't actually exist. This was digested and demonstrated in a karma issue which turned out to be user (my) error.
To stop the tests repeating we needed to update the frameworks array in the karma.conf.js and reduce the number of framework references and use the plugins instead which were already referenced.
frameworks: ['mocha', 'chai', 'sinon-chai', '#angular/cli'],
becomes
frameworks: ['mocha', '#angular/cli'],
Resolution
Stop the tests repeating and the beforeEach will behave as expected. A working commit can be found here.