Passing karma configuration object from gulpfile - gulp

I have a karma.conf.js file that exports a function that takes a config object and applies a bunch of configurations to that object.
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
...
If I start karma from the command line like this: karma start, it runs correctly. Clearly the karma start function is inserting the required config object when it calls the function exported by karma.conf.js.
I am trying to start it with a gulp task that looks like this:
gulp.task('test', function (done) {
var karma = require('karma').server;
var karmaConf = require('./karma.conf.js')();
karma.start(karmaConf, done);
});
This gives me an error because the config parameter is missing.
Two questions:
How can I get the karma config object to include as a parameter, and
Is there a better way to do this?

try this:
gulp.task('test', function(done) {
var Server = require('karma').Server;
new Server({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done).start();
});

I am aware this question is a little old, but I found it when I was about to post my own q/a to something similar. The main difference being that I'm not working with gulp, but am just using Karma's public API directly. I'm still stuck using Karma v0.12, but it doesn't look like the spec has changed in this regard. It still requires an ordinary object, and my config file exports a function, just like in the OP's situation.
The main problem with the sample in the question is it tries calling the config function without providing any arguments. That is probably what is throwing the error. In particular, the config function expects a single input config, and calls config.set(actualConfigObject). What I did was write a function of my own that provides a minimally suitable object.
All that is needed is to ensure that what is passed in to the config function has a set function that in some way captures its first argument for later use. I actually ended up wrapping all that in a function that returns the argument for convenience:
function extractConfig(configFunction) {
var last;
var shell = {
set: function (input) { last = input; }
};
configFunction(shell);
return last;
}
Then I can call this with my required config file:
var config = extractConfig(require('./local-karma.conf.js'));
Which got my tests running. I have noticed that something is slightly off, since I override the logging level in my config, but the API seems to be using config.LOG_DEBUG regardless. But that's the only problem I've had so far. Though this unanswered question seems to also be doing something similar, but with less successful results.

Related

Jest Unable to Parse Image Files

I'm trying to set up the configuration and mock files for jest to parse/ignore image files in order for the tests to pass. Just about every online resource leads me to the jest docs located: https://jestjs.io/docs/webpack#handling-static-assets
which tell you exactly how to handle the situation. However, not in my case. I've tried both options of creating mock files and using a transformer.
My current jest.config.js:
module.exports = {
projects: [
{
displayName: 'Unit',
testMatch: ["**/?(*.)+(spec|test).[tj]s?(x)"],
setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
testPathIgnorePatterns: ["<rootDir>/.next/", "<rootDir>/node_modules/", "<rootDir>/cypress/"],
moduleFileExtensions: ["js", "jsx", "ts", "tsx"],
moduleDirectories: ["node_modules", "bower_components", "shared"],
moduleNameMapper: {
"^.+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
'^.+\\.(css|sass|scss)$': '<rootDir>/__mocks__/styleMock.js'
},
// transform: {
// "\\.js$": "jest",
// "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/fileTransformer.js"
// //'^.+\\.(js|jsx|ts|tsx)$': ['babel-jest', { presets: ['next/babel'] }],
// }
},
{
displayName: 'Pacts',
testMatch: ["**/?(*.)+(pacttest).[tj]s?(x)"],
testPathIgnorePatterns: ["<rootDir>/.next/", "<rootDir>/node_modules/", "<rootDir>/cypress/"],
watchPathIgnorePatterns: ["pact/logs/*", "pact/pacts/*"],
}
],
};
my fileMock.js:
module.exports = 'test-file-stub';
My styleMock.js:
module.exports = {};
My fileTransformer.js:
const path = require('path');
module.exports = {
process(src, filename, config, options) {
return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';';
},
};
//export default module.exports;
my directory:
I've been bouncing back and forth trying different options in the configurations but they pretty much all lead me to the same two errors, one when I try to use the transformer, and another without. With the transformer commented out, I get 2 errors thrown at the fileMock.js file:
TypeError: Invalid URL: test-file-stub
Failed to parse src "test-file-stub" on next/image
Both of these are referring to the suggested string for the mock. I initially thought that maybe the string was a placeholder for code to actually handle something. But after some reading, my understanding is that it's actually just supposed to be a string there. Perhaps it's a specific string dependent on my environment? And next/image is where I'm importing the image component from.
I'm prioritizing the mocking (please correct me if I'm wrong) because my understand is the mock tells jest to ignore the image file and proceed with the rest of the test while the transformer actually attempts to change the file type from js to jpg or png or whatever filetype the image is. However, I'm trying everything I can. When I try to the run the tests with the transformer portion uncommented I receive an error before any tests are even run stating:
TypeError: Jest: a transformm must export something.
(which is why there is a commented out export default statement.)
This is my first time ever attempting anything like this and I think I've reached a point where I cannot think of anything else to try. If anybody has experienced anything like this please lay some knowledge on me. I'm not sure if I have the mockfiles set up incorrectly or if it's something in the configurations.
Thanks.
I was able to work around this by creating an image URL here:
https://www.base64-image.de/
and replacing the "test-file-stub" string with the generated URL string.
module.exports = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAABhWlDQ1BJQ0MgcHJvZmlsZQAAKJF9kT1Iw0AcxV/TSotUHeyg4pChOogFURFHrUIRKoRaoVUHk0s/hCYNSYuLo+BacPBjserg4qyrg6sgCH6AuLk5KbpIif9LCi1iPDjux7t7j7t3gFAvMc0KjAGaXjFTibiYya6IwVeE0I9ujCAgM8uYlaQkPMfXPXx8vYvxLO9zf44uNWcxwCcSzzDDrBCvE09tVgzO+8QRVpRV4nPiUZMuSPzIdcXlN84FhwWeGTHTqTniCLFYaGOljVnR1IgniaOqplO+kHFZ5bzFWStVWfOe/IXhnL68xHWag0hgAYuQIEJBFRsooYIYrTopFlK0H/fwDzh+iVwKuTbAyDGPMjTIjh/8D353a+Unxt2kcBzoeLHtjyEguAs0arb9fWzbjRPA/wxc6S1/uQ5Mf5Jea2nRI6BnG7i4bmnKHnC5A/Q9GbIpO5KfppDPA+9n9E1ZoPcW6Fx1e2vu4/QBSFNXyRvg4BAYLlD2mse7Q+29/Xum2d8PVXFym6OczU4AAAAJcEhZcwAALiMAAC4jAXilP3YAAAAHdElNRQflCBkOKh9/wZ+SAAAAGXRFWHRDb21tZW50AENyZWF0ZWQgd2l0aCBHSU1QV4EOFwAAAAxJREFUCNdj+P//PwAF/gL+3MxZ5wAAAABJRU5ErkJggg==';

Read local JSON files when dynamically creating functional tests in Intern

I am creating functional tests dynamically using Intern v4 and dojo 1.7. To accomplish this I am assigning registerSuite to a variable and attaching each test to the Tests property in registerSuite:
var registerSuite = intern.getInterface('object').registerSuite;
var assert = intern.getPlugin('chai').assert;
// ...........a bunch more code .........
registerSuite.tests['test_name'] = function() {
// READ JSON FILE HERE
var JSON = 'filename.json';
// ....... a bunch more code ........
}
That part is working great. The challenge I am having is that I need to read information from a different JSON file for each test I am dynamically creating. I cannot seem to find a way to read a JSON file while the dojo javascript is running (I want to call it in the registerSuite.tests function where it says // READ JSON FILE HERE). I have tried dojo's xhr.get, node's fs, intern's this.remote.get, nothing seems to work.
I can get a static JSON file with define(['dojo/text!./generated_tests.json']) but this does not help me because there are an unknown number of JSON files with unknown filenames, so I don't have the information I would need to call them in the declare block.
Please let me know if my description is unclear. Any help would be greatly appreciated!
Since you're creating functional tests, they'll always run in Node, so you have access to the Node environment. That means you could do something like:
var registerSuite = intern.getPlugin('interface.object').registerSuite;
var assert = intern.getPlugin('chai').assert;
var tests = {};
tests['test_name'] = function () {
var JSON = require('filename.json');
// or require.nodeRequire('filename.json')
// or JSON.parse(require('fs').readFileSync('filename.json', {
// encoding: 'utf8'
// }))
}
registerSuite('my suite', tests);
Another thing to keep in mind is assigning values to registerSuite.tests won't (or shouldn't) actually do anything. You'll need to call registerSuite, passing it your suite name and tests object, to actually register tests.

RequireJS: Uglification Not Working

I must be making a mistake somewhere, but it's not being written to stdout during optimization. I'm trying to optimize a file via requirejs, but the output isn't being minified. According to the documentation, UglifyJS should minify the code.
At any rate, the following code is trivial, but it isolates the problem.
src/index.js:
require(['config'], function () {
require(['myMod'], function (myMod) {
console.log(myMod.x());
})
})
src/myMod.js:
define(function () {
let myMod = {
x: 5
};
return myMod;
})
src/config.js:
define(function () {
require.config({
baseUrl: 'src'
});
})
And here's the gulp task that is performing the optimization:
gulp.task('optimize', function (cb) {
let config = {
appDir: 'src',
dir: 'dist/src',
generateSourceMaps: true,
preserveLicenseComments: false,
removeCombined: true,
baseUrl: './',
modules: [{
name: 'index',
include: ['myMod']
}]
}
let success = function (buildResponse) { console.log(buildResponse); cb() },
error = function (err) { console.log(err); cb(err) }
rjs.optimize(config, success, error)
})
After running the task, dist/src/index.js has all of the other modules included in it. However, it's not minified, and none of the variables have been renamed. Instead, it's as if the files were just concatenated, nothing more. Could someone tell me (1) why is it not being minified? (2) is UglifyJS throwing an error? If so, is there a way to see it when the gulp task is being run?
EDIT Here's a link to RequireJS docs where it talks about using the optimizer in node, which is done in the gulp task mentioned above. It's at the bottom under "Using the optimizer as a node module".
http://requirejs.org/docs/node.html
RequireJS' optimizer bundles UglifyJS2. UglifyJS2 does not handle ES6 or higher. If I take the options you use in your gulpfile, and plunk them into a separate file that I name options.js, and issue this command:
$ ./node_modules/.bin/r.js -o options.js
Then I get this output:
Tracing dependencies for: index
Uglify file: /tmp/t33/dist/src/index.js
Error: Cannot uglify file: /tmp/t33/dist/src/index.js. Skipping it. Error is:
SyntaxError: Unexpected token: name (myMod)
If the source uses ES2015 or later syntax, please pass "optimize: 'none'" to r.js and use an ES2015+ compatible minifier after running r.js. The included UglifyJS only understands ES5 or earlier syntax.
index.js
----------------
config.js
index.js
myMod.js
As you can see, UglifyJS does fail to minify your file, and RequireJS just skips the minification step for that file. Since this is not an outright error, the file is still output, just not minified.
If you change let to var in myMod.js, then the issue disappears.
Unfortunately, since this is not an execution failure (r.js still runs, it just does not minify the file), the error is not signaled to the errback handler you pass to rjs.optimize. I don't see a way to catch such error in a Gulpfile. The safe thing to do is to set optimize: "none" and perform the minification as an additional build step after running rjs.optimize.
I had also run into the same issue where require.js's optimizer (r.js) was combining different modules, but, it was not minify-ing the merged file. Although my run time environment is different from yours (using Java's Nashorn engine), this error was visible on my console :
If the source uses ES2015 or later syntax, please pass "optimize: 'none'" to r.js and use an ES2015+ compatible minifier after running r.js. The included UglifyJS only understands ES5 or earlier syntax.
Also, this error does not stop the optimizer from combining the files, it's just that the optimizer will not be able to mini-fy the merged file.

Papa Parse reading CSV locally

Can someone point to or show me a working example of Papa Parse reading a csv file.
When I try to use :
Papa.parse(file, {
complete: function(results) {
console.log("Finished:", results.data);
}
});
the file name is returned in the array instead of the data within. None of the internet examples actually work. The official demo works correctl inspecting its code I cant find it making use of the above strangely.
As #Matt mentioned in his comment, the trick is not to pass a file name, but a file object. This also was not intuitive to me at first, so here is a quick solution:
var data;
function parse() {
var file = document.getElementById('myDOMElementId').files[0];
Papa.parse(file, {
header: true,
dynamicTyping: true,
complete: function(results) {
console.log("Finished:", results.data);
data = results.data;
}
});
}
Note that you have to call the results in this way when working with a local file. If you want to work with the results elsewhere, assign it to a global variable.
I have faced the same problem and it was solved by 2 actions:
1- Adding a callback function
2- connecting to a local oython server/changing browser's security settigns
Check this:
https://github.com/mrdoob/three.js/wiki/How-to-run-things-locally
I did not pass an object but a string with the file name/path and it worked for me.

"this" in underscore is undefined after compiling with browserify and debowerify

So first.. I have next gulp task:
gulp.task('js', function() {
browserify('./src/js/main.js')
.bundle()
.on('error', onError)
.pipe( source('main.js') )
.pipe( gulp.dest(path.build.js) );
});
and package.json:
{
"browserify": {
"transform": [
["babelify", { "presets": ["es2015"] }],
"debowerify"
]
},
}
I am importing Backbone in main.js (or only underscore... it doesn't matter)
import Backbone from 'backbone';
And in console I am getting error
Uncaught TypeError: Cannot read property '_' of undefined
I checked code and found that in underscore sources at start of library root is undefined
// Establish the root object, `window` in the browser, or `exports` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
I think the problem is that debowerify or babelfy is wrapping code in some function. But also if I use node modules without debowerify all works fine. But I want to use bower.
So how to fix this problem?
To any future visitors to this question,
this is similar to Underscore gives error when bundling with Webpack
The gist of the issue is that babel is probably running the underscore.js code, since underscore.js uses this, and in es6 this is undefined when outside of a function, naturally this._ fails.
In code I've fixed the issue by ensuring that babel does not run on node_modules.
In my case the same error arose when using just browserify with underscore. I've workarounded issue by switching from underscore to lodash. They are in general (surely not fully) compatible, but at the worst I'd rather copy some missing function from underscore sources than live with its deisolated load approach.