Using karma-typescript with graphql-tag loader - graphql

I am trying to run tests written in TypeScript using tape and the karma-typescript loader.
In my project I use webpack with graphql-tag/loader and import the queries directly into my TypeScript files like:
import myQuery from "../query/hello.graphql";
These imports are causing issues when I try and run the tests.
module.exports = function (config) {
config.set({
frameworks: ["tap", "karma-typescript"],
files: [
"src/**/*.ts",
"src/**/*.tsx",
"query/**/*.graphql"
],
preprocessors: {
"src/**/*.ts": ["karma-typescript"],
"src/**/*.tsx": ["karma-typescript"]
},
karmaTypescriptConfig: {
compilerOptions: {
"skipLibCheck": true,
"allowSyntheticDefaultImports": true
},
bundlerOptions: {
transforms: [
require("karma-typescript-es6-transform")()
]
}
},
reporters: ["progress", "karma-typescript"],
browsers: ["Firefox"]
});
};
I guess that I would ideally like to perform a second transform on the .graphql files. Based on the approach used in jest-transform-graphql, I tried adding another transform:
function (context, callback) {
if (/\.graphql$/.test(context.module)) {
context.source = loader.call({ cacheable() { } }, context.source);
return callback(undefined, true);
}
return callback(undefined, false);
}
But I still get errors like:
{
"message": "SyntaxError: unexpected token: identifier\nat query/hello.graphql:1:6\n\n",
"str": "SyntaxError: unexpected token: identifier\nat query/hello.graphql:1:6\n\n"
}
How can I apply the transformation to the graphql files, so that I don't get syntax errors from them in the browser?

Related

How do I fix sitemap errors?

Sitemap Doesn't work
I can't get the site map URL and I can't use the /sitemap.xml URL
How do I fix it??
siteMetadata: {
siteUrl: siteAddress.href, // which is "https://www.example.com/"
},
{
resolve: `gatsby-plugin-sitemap`,
options: {
head: true,
output: `/sitemap.xml`,
}
Have you tried building your project? From the docs:
NOTE: This plugin only generates output when run in production mode! To test your sitemap, run: gatsby build && gatsby serve
In addition, your plugin's options are not valid: head should be createLinkInHead. A full sample with queries should look like:
{
resolve: `gatsby-plugin-sitemap`,
options: {
output: `/some-other-sitemap.xml`,
createLinkInHead: true,
exclude: [`/category/*`, `/path/to/page`],
query: `
{
wp {
generalSettings {
siteUrl
}
}
allSitePage {
nodes {
path
}
}
}`,
resolveSiteUrl: ({site, allSitePage}) => {
return site.wp.generalSettings.siteUrl
},
serialize: ({ site, allSitePage }) =>
allSitePage.nodes.map(node => {
return {
url: `${site.wp.generalSettings.siteUrl}${node.path}`,
changefreq: `daily`,
priority: 0.7,
}
})
}
}
Alternatively, you can use gatsby-plugin-advanced-sitemap which has more customizable options.

Disable cache-loader in webpack 4 vue cli 3

I am using a vue-cli 3/webpack 4 project .
My build is generated on AWS Codebuild which starts a new VM instance for each build.
Cache -loader in webpack caches the results of babel-loader, vue-loader and terser. But since I run a new instance VM every time I don’t take advantage of this.
If the caching itself has some overhead ,it’s better I turn it off then as suggested in some places like here.
How do I configure webpack via vue.conf object to remove the cache loader .
Thanks
My project generated webpack config for production is
rules: [
/* config.module.rule('vue') */
{
test: /\.vue$/,
use: [
/* config.module.rule('vue').use('cache-loader') */
{
loader: 'cache-loader',
options: {
cacheDirectory: '/Users/digitalsuppliers/work/new_build_branch/bmsconsole-client/node_modules/.cache/vue-loader',
cacheIdentifier: '22f91b09'
}
},
/* config.module.rule('vue').use('vue-loader') */
{
loader: 'vue-loader',
options: {
compilerOptions: {
preserveWhitespace: false
},
cacheDirectory: '/Users/digitalsuppliers/work/new_build_branch/bmsconsole-client/node_modules/.cache/vue-loader',
cacheIdentifier: '22f91b09'
}
}
]
},
{
test: /\.jsx?$/,
exclude: [
function () { /* omitted long function */ }
],
use: [
/* config.module.rule('js').use('cache-loader') */
{
loader: 'cache-loader',
options: {
cacheDirectory: '/Users/digitalsuppliers/work/new_build_branch/bmsconsole-client/node_modules/.cache/babel-loader',
cacheIdentifier: 'e8179b56'
}
},
/* config.module.rule('js').use('thread-loader') */
{
loader: 'thread-loader'
},
/* config.module.rule('js').use('babel-loader') */
{
loader: 'babel-loader'
}
]
}
One solution is to disable cache either completely or only in production/development based on condition.
In order to use it open your vue.config-js and write there
module.exports = {
chainWebpack: config => {
// disable cache for prod only, remove the if to disable it everywhere
// if (process.env.NODE_ENV === 'production') {
config.module.rule('vue').uses.delete('cache-loader');
config.module.rule('js').uses.delete('cache-loader');
config.module.rule('ts').uses.delete('cache-loader');
config.module.rule('tsx').uses.delete('cache-loader');
// }
},
In this example I've commented out the condition, so cache-loader is not used at all.
if you mount the vue-component by routing, would you trying to import component to async-way? not sync-way.
when router/index.js loaded..
then may be help you.
ex.
component: () => ({
component: import('#/views/your/pageComponent.vue'),
loading: this.loading,
error: this.error,
delay: this.delay,
timeout: this.timeout,
})

Laravel + VueJs + Webpack + Karma = world of pain

Is it possible to write unit tests for VueJs if you are using Laravel's Elixir for your webpack configuration?
VueJs 2x has a very simple example for a component test: Vue Guide Unit testing
<template>
<span>{{ message }}</span>
</template>
<script>
export default {
data () {
return {
message: 'hello!'
}
},
created () {
this.message = 'bye!'
}
}
</script>
and then...
// Import Vue and the component being tested
import Vue from 'vue'
import MyComponent from 'path/to/MyComponent.vue'
describe('MyComponent', () => {
it('has a created hook', () => {
expect(typeof MyComponent.created).toBe('function')
})
it ...etc
})
and gives an example of a karma conf file here: https://github.com/vuejs-templates
But the Karma configuration file requires a webpack configuration file
webpack: webpackConfig,
The only problem is the Laravel's Elixir is creating the webpack configuration so it can't be included.
I have tried creating another webpack configuration file based on the example from https://github.com/vuejs-templates/webpack.
Something like this:
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'build.js'
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
// Since sass-loader (weirdly) has SCSS as its default parse mode, we map
// the "scss" and "sass" values for the lang attribute to the right configs here.
// other preprocessors should work out of the box, no loader config like this necessary.
'scss': 'vue-style-loader!css-loader!sass-loader',
'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
}
// other vue-loader options go here
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
}
},
devServer: {
historyApiFallback: true,
noInfo: true
},
performance: {
hints: false
},
devtool: '#eval-source-map'
}
and included it like...
// Karma configuration
// Generated on Wed Mar 15 2017 09:47:48 GMT-0500 (CDT)
var webpackConf = require('./karma.webpack.config.js');
delete webpackConf.entry;
module.exports = function(config) {
config.set({
webpack: webpackConf, // Pass your webpack.config.js file's content
webpackMiddleware: {
noInfo: true,
stats: 'errors-only'
},
But I am getting errors that seem to indicate that webpack isn't doing anything.
ERROR in ./resources/assets/js/components/test.vue
Module parse failed: /var/www/test/resources/assets/js/components/test.vue Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
| <template>
| <span >{{test}}</span>
| </template>
Ok, I got this to work. Couple of things that might help.
I was originally running gulp, and trying to run tests in my vagrant box, to try to match the server configuration. I think that makes it much harder to find examples and answers on the internet.
Ok, so the main problem I was having is that webpack wasn't processing my components included in my test files. I copied the webpack config out of the laravel-elixir-vue-2/index.js node module directly into the Karma configuration file and it started working.
The key is that karma-webpack plugin needs both the resolve and module loader configuration settings (resolve with alias and extensions) for it to work.
Hope this helps someone.
karma.conf.js:
module.exports = function (config) {
config.set({
// to run in additional browsers:
// 1. install corresponding karma launcher
// http://karma-runner.github.io/0.13/config/browsers.html
// 2. add it to the `browsers` array below.
browsers: ['Chrome'],
frameworks: ['jasmine'],
files: ['./index.js'],
preprocessors: {
'./index.js': ['webpack']
},
webpack: {
resolve: {
alias: {
vue: 'vue/dist/vue.common.js'
},
extensions: ['.js', '.vue']
},
vue: {
buble: {
objectAssign: 'Object.assign'
}
},
module: {
loaders: [
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'file-loader',
query: {
limit: 10000,
name: '../img/[name].[hash:7].[ext]'
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 10000,
name: '../fonts/[name].[hash:7].[ext]'
}
}
]
}
},
webpackMiddleware: {
noInfo: true,
},
coverageReporter: {
dir: './coverage',
reporters: [
{ type: 'lcov', subdir: '.' },
{ type: 'text-summary' },
]
},
});
};
I ran into the exact same problem. The accepted answer did not fully work for me. The following solved my issue:
Install relevant loaders for webpack:
npm install --save-dev vue-loader file-loader url-loader
Create webpack config file (note the format). The accepted answer produced errors citing invalid format of the webpack.config.js file. At least with me it did.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.vue$/,
use: [
{ loader: 'vue-loader' }
]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
use: [
{
loader: 'file-loader',
query: {
limit: 10000,
name: '../img/[name].[hash:7].[ext]'
}
}
]
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
use: [
{
loader: 'url-loader',
query: {
limit: 10000,
name: '../fonts/[name].[hash:7].[ext]'
}
}
]
}
]
}
}
karma.conf.js
// Karma configuration
var webpackConf = require('./webpack.config.js');
delete webpackConf.entry
module.exports = function(config) {
config.set({
frameworks: ['jasmine'],
port: 9876, // web server port
colors: true,
logLevel: config.LOG_INFO,
reporters: ['progress'], // dots, progress
autoWatch: true, // enable / disable watching files & then run tests
browsers: ['Chrome'], //'PhantomJS', 'Firefox',
singleRun: true, // if true, Karma captures browsers, runs the tests and exits
concurrency: Infinity, // how many browser should be started simultaneous
webpack: webpackConf, // Pass your webpack.config.js file's content
webpackMiddleware: {
noInfo: true,
stats: 'errors-only'
},
/**
* base path that will be used to resolve all patterns (eg. files, exclude)
* This should be your JS Folder where all source javascript
* files are located.
*/
basePath: './resources/assets/js/',
/**
* list of files / patterns to load in the browser
* The pattern just says load all files within a
* tests directory including subdirectories
**/
files: [
{pattern: 'tests/*.js', watched: false},
{pattern: 'tests/**/*.js', watched: false}
],
// list of files to exclude
exclude: [
],
/**
* pre-process matching files before serving them to the browser
* Add your App entry point as well as your Tests files which should be
* stored under the tests directory in your basePath also this expects
* you to save your tests with a .spec.js file extension. This assumes we
* are writing in ES6 and would run our file through babel before webpack.
*/
preprocessors: {
'app.js': ['webpack', 'babel'],
'tests/**/*.spec.js': ['babel', 'webpack']
},
})
}
Then run karma start and everything should work.

Uncaught Error: Module name "lib/chai" has not been loaded yet for context: use require([])

i m using karma-mocha ..my karma.conf file is working with karma-jasmine...but not working with karma-mocha....my karma.conf file:--
module.exports = function(config){
config.set({
basePath : '../app',
preprocessors: {
'**/*.html':'ng-html2js'
},
ngHtml2JsPreprocessor: {
prependPrefix: '/'
},
files : [
'node_modules/jquery/**/*.js',
'lib/angular/angular.js',
'lib/angular/angular-*.js',
'../test/lib/angular-mocks.js',
'../test/lib/sinon-1.15.0.js',
'../test/chai/chai.js',
'js/**/*.js',
'../test/unit/**/*.js',
'**/*.html'
],
autoWatch : true,
frameworks: ['mocha','requirejs','chai'],
browsers : ['Chrome'],
plugins : [
'karma-chrome-launcher',
'karma-mocha',
'karma-ng-html2js-preprocessor',
'karma-requirejs',
'karma-chai'
],
junitReporter : {
outputFile: 'test_out/unit.xml',
suite: 'unit'
}
});
};
you are missing chai lib path files array in which is dependency to mocha.include it.
files : [
'node_modules/jquery/**/*.js',
'lib/angular/angular.js',
'lib/angular/angular-*.js',
'../test/lib/angular-mocks.js',
'../test/lib/sinon-1.15.0.js',
'../test/chai/chai.js',
'js/**/*.js',
'../test/unit/**/*.js',
'**/*.html'
],
I came across a similar situation just with Jasmine.
I'd like to introduce my solution.
Try it what is written in the error message. There is a link to a website: http://requirejs.org/docs/errors.html#notloaded
//If this code is not in a define call,
//DO NOT use require('foo'), but use the async
//callback version:
require(['foo'], function (foo) {
//foo is now loaded.
});
My case written for Jasmine in Coffee script looks like this:
sinon = require(['sinon', 'jasmine-sinon']) (foo)->
Now I can use sinon as an object in my unit test and can also follow the documentation of sinon, as well as jasmin-sinon.

How to test browserify project using karma/jasmine

I'm totally new to the concept of testing, and i need one solid example on how to do it in my project:
I have a gulp file goes like this (Not all of it, just the important portions)
gulp.task('bundle', function() {
gulp.src('public/angular-app/main.js')
.pipe(browserify({
debug: true
}))
.pipe(gulp.dest('public/min-js'));
});
This is a slight portion of my main.js:
'use strict';
angular.module('myApp', [
'ui.router',
'ui.bootstrap',
'ngSanitize',
'ngFx',
...
], ['$interpolateProvider',
function($interpolateProvider) {
$interpolateProvider.startSymbol('{{');
$interpolateProvider.endSymbol('}}');
}
])
.config(require('./config/routes'))
.config(require('./config/authInterceptor'))
.run(require('./config/runPhase'))
.run(require('./config/xeditable'))
.controller('homeController', require('./controllers/homeController'))
.controller('modalInstanceCtrl', require('./controllers/modalInstanceCtrl'))
.controller('modalparticipantCtrl',require('./controllers/modalParticipantCtrl'))
.controller('generatorController',require('./controllers/generatorController'))
.controller('navController', require('./controllers/navController'))
.controller('signInController', require('./controllers/signInController'))
.controller('pricingController', require('./controllers/pricingController'))
.controller('howItWorksController',require('./controllers/howItWorks'))
...
Now this is my config file for karma:
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'],
// list of files / patterns to load in the browser
files: [
'public/vendor/jquery/dist/jquery.js',
'public/vendor/angular/angular.js',
'public/vendor/angular-mocks/angular-mocks.js',
'public/angular-app/**/*.js',
'test/**/*Spec.js'
],
// list of files to exclude
exclude: [
],
When i run karma with karma start this is what i get:
Uncaught reference error:require is not defined
at root/public/angular-app/main.js
So my question is simple, how can i do tests, for example, on my homeController...
//update
So I updated my test file to this:
describe("An Angularjs test suite",function(){
var target, rootScope;
beforeEach(inject(function($rootScope) {
rootScope = $rootScope;
// Mock everything here
spyOn(rootScope, "$on")
}));
beforeEach(inject(function(homeController) {
target = homeController;
}));
it('should have called rootScope.$on', function(){
expect(rootScope.$on).toHaveBeenCalled();
});
});
and my config file to this:
// list of files / patterns to load in the browser
files: [
'public/vendor/jquery/dist/jquery.js',
'public/vendor/angular/angular.js',
'public/vendor/angular-mocks/angular-mocks.js',
'public/min-js/main.js',
'test/**/*Spec.js'
],
// list of files to exclude
exclude: [
],
browserify: {
watch: true,
debug: true
},
preprocessors: {
'test/*': ['browserify']
},
Still nothing works, first he says 'unknown provider homeControllerProvider',
Now if i delete them lines:
beforeEach(inject(function(homeController) {
target = homeController;
}));
it still gives me error, expected spy $on to be called, How do i fix this?
You need to inform Karma to run Browserify before running tests.
You can add this in your Karma config:
{
browserify: {
watch: true,
debug: true
},
preprocessors: {
'test/*': ['browserify']
}
}
Karma config file reference: http://karma-runner.github.io/0.12/config/configuration-file.html
Or have a look at one of of my projects that uses Karma for testing: smild.

Resources