Load Json Fixture in Karma/Mocha - javascript

I am using Karma with Mocha and karma-fixture. If I go into debug when I run tests, I can see the file is loaded in the server. If I changed the config included:true, then I can see it's loaded on the console. The extension is changed to .js (rather than .json) and if I view source on the file (in browser window) the json is wrapped in a function -- so it seems like everything is happening as described in the documentation. However, I get an error that the file cannot be found. I have included the relevant configs and errors below.
Update 1
I was able to load the fixture with require -- which I'm using anyway to manage and load dependencies. The data is assigned to an array like this: __json__['test/fixtures/json-data/querybrowser']. I would still be interested in knowing why I can't use the fixture.load() function. I feel like I am missing a simple detail here.
Thank you!
The configuration:
The file is located here, pathed from root of my project: \test\fixtures\json-data\querybrowser.json
Karma
files: [{pattern: 'test/fixtures/{,*/}*', watched: true, included: false, served: true}]
TEST spec
fixture.setBase('base/test/fixtures/json-data');
querybrowser_json = fixture.load('querybrowser.json');
The Error
Chrome 48.0.2564 (Windows 7 0.0.0) Query Browser Function Tests "before all" hook FAILED
ReferenceError: Cannot find fixture 'base/test/fixtures/json-data/querybrowser.js'
at Fixture._throwNoFixture (////node_modules/karma-fixture/lib/fixture.js:141:13)

Have you:
Made sure that you're including the JSON files in both your files array and your preprocessors array inside your karma config?
Made sure that you have transformPath property defined in jsonFixturesPreprocessor as per https://github.com/billtrik/karma-fixture/issues/10?
I had the same issue as you but doing these things fixed it for me.

Related

Excluding file from optimizing in Durandal build

I'm using Grunt to build the Durandal starter kit pro package.
It all works fine, except for one tiny detail. I would like to exclude one file (app-config below) from the optimizer and keep it as a non minified file when my build is done.
Based on other SO thread suggestions, I'm currently excluding it using empty:, which removes it from the optimized file as expected. However, when I open the built project I get an error in the console:
Uncaught Error: main missing app-config
options: {
name: '../lib/require/almond-custom',
baseUrl: requireConfig.baseUrl,
mainPath: 'app/main',
paths: mixIn({ }, requireConfig.paths, {
'almond': 'lib/require/almond-custom',
'app-config': 'empty:'
}),
optimize: 'none',
out: 'build/app/main.js',
preserveLicenseComments: false
}
Is almond the problem? I tried switching it to the full requirejs using include: ['path/to/require'], without success.
If you want to reproduce it locally you can either download the starter kit from the above link, or use a slightly configurated version which is closer to my example. Just run an npm install in the folder and you're all set.
I have downloaded you source code and do the following steps.
Extract zip file, open cmd and change the directory to this folder.
Run npm install to install all the dependencies.
Run grunt to start to build the project.
And when I open http://localhost:8999/ and saw the alert 1 which is alert(appConfig.foo); in your main.js.
After clicked Ok to hide the alert, the web page works fines. Any more input for you ?
So I am not sure how you are facing with this issue.
From the reference of the durandal issues found in this particular link
grunt-durandal
The main module controls the implementation of the durandal services
The link can be found in main.js
Here you can see the system.debug(true).You can remove it as written in the post here document.
The function as quoted in the article Overrides request execution timeout making it effectively infinite.
Also while using uglify in grunt the debug is set to false as per the documentation.
As per the documentation you need to set the system.debug(false)
Hope this might help a bit.
try:
....
paths: mixIn({ }, requireConfig.paths, {
'almond': ['lib/require/almond-custom', '!lib/require/almond-custom/app-config.js']
}),
....
just note the second path of app-config.js is correct. I think you should find your way, the above is a hint, if not a direct solution.

Add files to watch-list in karma preprocessor

Here is a repository created to demonstrate the issue:
brianmhunt/karma-rollup-preprocessor-issue-3
I'm trying to get karma-rollup-preprocessor working with Karma's builtin watch i.e. solve showpad/karma-rollup-preprocessor#3
In other words, in a preprocessor, I want to add files to Karma's watch list.
It's easy to get the list of files Rollup uses to compile. Rollup returns a list of files that it reads (ones one wants to watch), so in the preprocessor I am trying to add files to the list karma watches.
Basically I want to add this (or the working equivalent) to the preprocessor:
bundle.modules.forEach((module) => {
files.unshift({
pattern: module.id, /* The full file path, from Rollup */
watched: true,
included: false,
nocache: false,
served: false,
})
})
Where files is Karma's config.files or fileList or whatever place one needs to put the files being watched.
Doing the above with config.files, the files are indeed being added to the watcher, but .on(fileList.changeFile) fails the _isIncluded.
So it looks like the files also (or alternatively) must be added to the fileList.
Unfortunately when I try to add the fileList to the $inject, I get the error:
Error: Can not resolve circular dependency! (Resolving: preprocess -> preprocessor:rollup -> fileList -> preprocess).
I've looked at basically all the other preprocessors that look like they could also add includes, but I have found no indication of how to do it.
Is there a canonical way to add files Karma should watch from a preprocessor? Or otherwise how might one do this? This seems pretty clutch for a preprocessor in Karma, so it's surprising that it's not documented, apparent, or problematic in the other preprocessors.
EDIT Here's some more attempts:
I tried to add the watched patterns to the config.files in karma.conf i.e.
files: [
"spec/**/*.js",
{pattern:"src/**/*.js", included: false, watched: true}
]
But the src/* doesn't recompile when changed. The tests just re-run.
So I tried chokidar like this:
var server = new karma.Server(options)...
chokidar.watch("src/**/*.js")
.on('add', server.refreshFiles.bind(server))
.on('change', server.refreshFiles.bind(server))
I also tried it with a debounce, in case Karma was slower on the refresh, but it seems the tests won't re-run.
I rooted around karma-browserify for inspiration but it was a bit too convoluted to pick up without delving in.
I've issued a pull request to resolve this.
Until it is merged one can use my repo i.e. put "karma-rollup-preprocessor": "brianmhunt/karma-rollup-preprocessor" in package.json dependencies or devDependencies.
EDIT: Superceded by https://github.com/Kflash/karma-rollup-plugin

Read a HTML file in a Karma+Jasmine test

I have an Angular controller that defines an array of over 50 field names. Each of these should occur in an HTML file as both the id and ng-model of an input are present. I would like to test if I made no typos by reading and parsing the HTML file. Since I need to get the array, a Karma+Jasmine test seems ideal (with protractor I can't get that). What would be a good way to test this?
For both the FileReader and $http.get neither enter the success or error function, and with XMLHttpRequest I just get an empty string.
I already added a line
pattern: 'app/views/*.html', watched: false, included: false, served: true}
to karma.conf.js, that matches the file I want to read.
Any help is greatly appreciated.
1.You can use following preprocessor to render html
npm install karma-ng-html2js-preprocessor --save-dev
Add following into karma.config.js:
ngHtml2JsPreprocessor : {
moduleName:'templates'
},
2.Use $compile service of angular and create html which you want to test and add it to dom. Then you can perform any test on that html
var $body=$('$body');
afterEach(
$body.empty();
);
You could load the HTML-snippets as fixtures with jasmine-jquery. Don't wonder about the name, it's because the library also adds lots of custom jasmine matchers which are useful in combination with jQuery.
To use it, add the following in your karma config file to the files array:
// this is the path to your library if installed via bower
'../bower_components/jasmine-jquery/lib/jasmine-jquery.js',
// make the views available to the locally by karma started webserver
{pattern: 'views/*.html', watched: true, served: true, included: false},
For your tests, you have to define the path to your views and load them explicitly:
beforeEach(function () {
jasmine.getFixtures().fixturesPath = "base/views"; // path to your templates
jasmine.getFixtures().load('myHtmlSnippet.html'); // load a template
});
This will load an div with the id jasmine-fixtures directly into the body of the browser in which the tests run. The loaded fixture will be inserted into the div#jasmine-fixtures. Then you can simply access them with jQuery or by vanilla javascript.
After I had such the sample problem to call the "server"-data and don't use a mockup service.
I stumble over this entry:
E2E mock $httpBackend doesn't actually passThrough for me
Works fine, with this you can use $http.get and check your data.
If you're working with promises try also this: https://github.com/ThomasBurleson/jasmine-as-promised

test not running on karma/jasmine/require.js 'There is no timestamp for *lib*!' error

I change the code, extend some functionality and add new unittest for that. Now, when I run my unit tests with karma (test framework - jasmine), it throw me an error
'There is no timestamp for /libs/angular-bootstrap/ui-bootstrap-tpls.js!'
Uncaught Error: Script error for: angular-bootstrap
http://requirejs.org/docs/errors.html#scripterror
at http://localhost:9876/base/node_modules/karma-requirejs/lib/require.js?1379984163000:138
What I'm doing wrong?
It was my mistake completely. when using karma-requirejs you have main-test.js file where configure how to require.js get the files. I add reference to angular-bootstrap with mistake, that's why require.js couldn't find this file and throwing this mistake. So in my case this error means wrong file name provided.
It can be because it cannot access your source file. You should configure karma to serve scripts where require will look for them.
For example have the config in the karma conf
files:[{pattern: 'node_modules/**/*.js', included:false}]
The question is old, the OP already solved his problem by now, but I'll add my two cents:
From the error message (end of the first error line) we can conclude that you were including a paths (or deps) file in main-test.js with the .js extension.
In RequireJS, you need to call the file names without the extension, so your paths (or deps) would look more or less like this:
paths: {
'ui-bootstrap': 'libs/angular-bootstrap/ui-bootstrap-tpls' // <- without the extension
}

Require.js optimizer and variables in paths

I have a problem getting r.js to work the way we need it to.
I have the following problem: We have 2 domains (e.g. foo.de and bar.de) and different environments. Depending on what environment and what domain they are running on they need to load a different file from their origin servers. My initial solution was this:
// channelDomain and environmentPath get defined above this script
require.config({
paths: {
'fooscript': channelDomain+environmentPath
}
}
Testing this in the browser unoptimized works exactly as it should but the nightly build complained with:
[Error: Error: The config in mainConfigFile /absolute/path/app/public/js/main.js
cannot be used because it cannot be evaluated correctly while running in the
optimizer. Try only using a config that is also valid JSON, or do not use
mainConfigFile and instead copy the config values needed into a build file or
command line arguments given to the optimizer.
Source error from parsing: /absolute/path/app/public/js/main.js: ReferenceError:
channelDomain is not defined
I tried doing lots of things but I'm running out of ideas. I tried doing the empty: thing in the build file but that didn't work either. I'd be glad if someone could point me into the right direction.
Use two require.config in the same file. The optimizer will only read the first one, as James says here https://github.com/jrburke/r.js/issues/270#issuecomment-13112859, and it will work in the browser after optimization.
So at the end you will have something like this in main.js:
require.config({
//only configurations needed for the transpiler's optimization
});
require.config({
paths: {
'fooscript': channelDomain+environmentPath
}
});

Categories

Resources