I have two pipes in my Angular Projekt. The test for both of them look the same, and are just test for existance. One of them is failing with the error message: An error was thrown in afterAll\nUncaught TypeError: _this.handler.handle is not a function thrown
The test looks like the following:
it('create an instance', () => {
const pipe = new MyPipe();
expect(pipe).toBeTruthy();
});
Even when I change the code to not even creating the Pipe it still fails.
it('create an instance', () => {
expect(true).toBeTruthy();
});
So it seems to be something wrong with the test itself but I wasn't able to figure out why.
karma.conf.js
config.set({
basePath: '',
frameworks: ['jasmine', '#angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('#angular-devkit/build-angular/plugins/karma'),
require('karma-junit-reporter')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, 'coverage'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
reporters: config.angularCli && config.angularCli.codeCoverage
? ['progress', 'coverage-istanbul', 'junit']
: ['progress', 'kjhtml', 'junit'],
junitReporter: {
outputFile: 'test-results.xml'
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
You should ensure the following is true in your code:
in the "spec" you are not including HttpClientModule and instead use HttpClientTestingModule
See the SO post here regarding that one:
TypeError: _this.handler.handle is not a function error
Also ensure that any subscribe from a http request has an error block.
Wrong:
this.myservice.func().subscribe(result => {
// do stuff
})
Right:
this.myservice.func().subscribe(result => {
// do stuff
}, error => {
// process error
})
See the SO post regarding that one:
Angular5 / ng test ERROR : TypeError: this.handler.handle is not a function
(top answer)
Note this is especially true if you do some sort of service call in ngInit.
Related
With the following webpack.mix.js file
const mix = require("laravel-mix");
// Laravel Mix plugins for additional capabilities
require("laravel-mix-purgecss");
require("laravel-mix-criticalcss");
// CSS Plugins
const tailwindcss = require("tailwindcss");
const autoprefixer = require("autoprefixer");
const presetenv = require("postcss-preset-env");
mix.setPublicPath('../public_html/assets/')
.sass(pkg.paths.src.scss + "master.scss", "css/master.min.css")
.options({
processCssUrls: false,
postCss: [ tailwindcss('./tailwind.config.js') ],
})
.js(pkg.paths.src.js + "site.js", "js/site.min.js")
.sourceMaps()
.browserSync({
proxy: "domain.local",
notify: {
styles: {
top: 'auto',
bottom: '0'
}
},
files: [
"src/scss/*.scss",
"templates/*.twig",
"templates/**/*.twig",
"templates/*.js",
"templates/**/*.js"
]
});
// mix.disableSuccessNotifications();
if (mix.inProduction()) {
mix.webpackConfig({
plugins: [],
})
.criticalCss({
enabled: true,
paths: {
base: 'https://domain.local',
templates: './templates/_inline_css/',
suffix: '.min'
},
urls: [
{ url: '/', template: 'index' },
],
options: {
minify: true,
timeout: 1200000,
},
})
.version();
}
when I run npm run production I get:
98% after emitting HtmlCriticalWebpackPlugin(node:58149) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined.
What's confusing about this is that at one point this was working OK. My list of URLs is longer than what I've displayed above. And the first time I tried it, it successfully output CSS files but I was getting problems with timeouts so started doing a few at a time.
I was able to successfully run it two or three times before the above error appeared and now it won't compile anymore. I even went back and tried the same bundles I'd tried before but it wouldn't work the second time around.
I've also tried a similar set-up using Gulp but get the same error.
Has anyone else ever got this? How did you solve it?
I have been trying to trigger the browser and open Google using Karma with Jasmine.
Karma console is giving the following error:
Karma error message
Selenium-standalone log:
Selenium standalone log
Karma.conf.js->
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
plugins: [
'karma-browserify',
'karma-jasmine',
'karma-firefox-launcher'
],
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['browserify','jasmine'],
// list of files / patterns to load in the browser
files: [
'../../../scripts/jasmineTest.spec.js'
],
// list of files / patterns to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'../../../scripts/jasmineTest.spec.js' : [ 'browserify' ]
},
browserify: {
debug: true,
// transform: [ 'brfs' ]
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Firefox'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
My Jasmine script:
var wdio = require('../webdriverio')
describe("Jasmine test", function(){
var client = {}
client = wdio.remote({
desiredCapabilities: {
browserName: 'firefox'
}
})
client.init()
client.url("https://www.google.co.in")
it("test-1", function(done){
// expect(false).not.toBe(true)
// expect(2).toEqual(2)
done()
})
it("test-2", function(done){
// var a = ['A','B','C']
// expect(a).toContain('D')
done()
})
})
This is my first time making a project with Jasmine, and I'm following a tutorial but right off the bat having issues.
I've installed jasmine-node, typings, and typescript. I also ran:
typings install dt~jasmine --save-dev --global
For Jasmine typescript.
Now I have a test file in my ./spec folder that looks like this:
import { async, ComponentFixture, TestBed } from '#angular/core/testing';
import { DatePickerComponent } from '../src/components/via-datepicker.component';
import * as moment from 'moment';
const Moment: any = (<any>moment).default || moment;
describe('DatePickerComponent', () => {
let component: DatePickerComponent;
let fixture: ComponentFixture<DatePickerComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ DatePickerComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(DatePickerComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should open when clicked', () => {
fixture.debugElement.nativeElement.querySelector('body').click();
fixture.whenStable().then(() => {
expect(component.opened);
});
component.close();
});
describe('While open', () => {
beforeEach(() => {
component.open();
});
describe('Pressing the "Today\'s date" button', () => {
it('should set the value of the picker to the current date and close it', () => {
fixture.debugElement.nativeElement.querySelector('.datepicker-buttons button').click();
expect(Moment().isSame(component.value, 'day') && Moment().isSame(component.value, 'month'));
expect(!component.opened);
});
});
describe('Clicking on a date', () => {
it('should change the value of the picker and close it', () => {
let oldValue: any = component.value;
fixture.debugElement.nativeElement.querySelectorAll('.day')[10].click();
expect(!component.opened);
expect(!component.value.isSame(oldValue));
});
});
});
});
But when I run this command:
node_modules/jasmine-node/bin/jasmine-node spec
I get this result:
Finished in 0 seconds
0 tests, 0 assertions, 0 failures, 0 skipped
So clearly my test file is being ignored. Or maybe I'm missing some library? Would I receive an error message if this were the case? The main issue here is that I'm not being given much direction as to what the issue is, other than Jasmine doesn't seem to "see" the test file for some reason.
Just trying to move forward with my project. Any advice would be greatly appreciated.
It appears as if your test runner doesn't know that you're trying to run typescript tests. Are you using Karma as your test runner? If so, you need to add your Typescript files to your karma.config file and install karma-typescript and configure your karma.config file similar to what is shown below. Pay close attention to the addition to the frameworks, files, and preprocessors sections.
karma.config
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine', 'karma-typescript'],
// list of files / patterns to load in the browser
files: [
{ pattern: "app/tests/**/*.spec.js"}
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
"app/tests/**/*.spec.ts": ["karma-typescript"]
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: [],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true
})
};
I think I have everything set up properly. I followed the specs of the Karma Tutorial for RequireJS, but everything I've tried seems to result in the same error.
It appears that my test-main.js file is being loaded since a console.log() will fire. However, in the Object.keys loop, the files will get listed, but TEST_REGEXP fails so the allTestFiles ends up being an empty array. I'm sure it's something silly, but it's created just like the Tutorial - with the exception of using node_modules for jquery, require, underscore.
My test-main.js file:
var allTestFiles = [];
var TEST_REGEXP = /test\.js$/;
var pathToModule = function(path) {
return path.replace(/^\/base\//, '').replace(/\.js$/, '');
};
Object.keys(window.__karma__.files).forEach(function(file)
{
if(TEST_REGEXP.test(file))
{
// Normalize paths to RequireJS module names
allTestFiles.push(pathToModule(file));
}
});
if(console) console.log(allTestFiles);
require.config(
{
// Karma serves files under /base, which is the basePath from the config file
baseUrl: '/base/src',
paths:
{
'jquery':'../node_modules/jquery/dist/jquery',
'underscore':'../node_modules/underscore/underscore-min'
},
shim:
{
'underscore': { exports: '_' }
},
// dynamically load all test files
deps: allTestFiles,
// kick off jasmine, as it is asynchronous
callback: window.__karma__.start
});
My karma.conf.js file:
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine', 'requirejs'],
// list of files / patterns to load in the browser
files: [
'test/test-main.js',
{pattern: 'node_modules/jquery/dist/jquery.js', included: false},
{pattern: 'src/*.js', included: false},
{pattern: 'test/**/*Spec.js', included: false}
],
// list of files to exclude
exclude: [
'src/main.js'
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
I came across a solution to the problem.
I ended up changing my test-main.js file above the require.config section to this:
// Karma RequireJS configuration
var tests = [];
for (var file in window.__karma__.files) {
if (/Spec\.js$/.test(file)) {
tests.push(file);
}
}
If I simply changed TEST_REGEXP to /Spec\.js$/ I ended up getting a timestamp error. I don't know why. More interesting is why following the guide produces errors. But it is all working now.
I'm trying to perform a basic functional test:
define([
'intern!object',
'intern/chai!assert',
'../Request',
'require'
], function (registerSuite, assert, Request, require) {
var request,
url = 'https://github.com/theintern/intern';
registerSuite({
name: 'demo',
'submit form': function () {
return this.remote
.get(require.toUrl('./fixture.html'))
.findById('operation')
.click()
.type('hello, world')
.end()
.findById('submit')
.click()
.end()
.setFindTimeout(Infinity)
.findById('result')
.setFindTimeout(0)
.text()
.then(function (resultText) {
assert.ok(resultText.indexOf(
'"hello, world" completed successfully') > -1,
'On form submission, operation should complete successfully');
});
}
});
});
(Example from the intern.js documentation)
https://github.com/theintern/intern/wiki/Writing-Tests-with-Intern
My intern.js configuration file is as followed:
define({
proxyPort: 9000,
proxyUrl: 'http://localhost:9000/',
capabilities: {
'selenium-version': '2.41.0'
},
environments: [
{ browserName: 'chrome'}
],
maxConcurrency: 3,
tunnel: "BrowserStackTunnel",
webdriver: {
host: 'http://hub.browserstack.com/wd/hub',
username: 'XXXXX',
accessKey: 'XXXXX'
},
useSauceConnect: false,
loader: {
packages: [
{
name: "dojo",
location: 'vendor/dojo'
}
]
},
suites: [ "tests/test" ],
excludeInstrumentation: /^(?:tests|node_modules)\//
});
When I run my test, it seems that the connection is being made with browserstack, but my test keep failing:
-> ./node_modules/.bin/intern-runner config=tests/intern
Listening on 0.0.0.0:9000
Starting tunnel...
BrowserStackLocal v2.2
Ready
Initialised chrome 35.0.1916.114 on XP
Test main - index - test FAILED on chrome 35.0.1916.114 on XP:
TypeError: Cannot read property 'get' of null
at Test.registerSuite.test <tests/test.js:11:17>
at Test.run <__intern/lib/Test.js:154:19>
at <__intern/lib/Suite.js:212:13>
at signalListener <__intern/node_modules/dojo/Deferred.js:37:21>
at Promise.then.promise.then <__intern/node_modules/dojo/Deferred.js:258:5>
at <__intern/lib/Suite.js:211:46>
I assumed that the WebDriver is not loaded, how may I access the remote browser environment inside my functional test?
Only functional tests interact with a WebDriver client and have a remote property. In your config, include your test suite in the functionalSuites array, not suites.
Note that the webdriver property is no longer used, so if you want to specify your username and access key in the config file you should use tunnelOptions instead.
tunnelOptions: {
username: <username>,
accessKey: <accessKey>
}
The tunnel knows the proper hostname to use by default, so you don't need to provide that.