billtrik / karma-fixture Goto Github PK
View Code? Open in Web Editor NEWA plugin for the Karma test runner that loads .html and .json fixtures
License: MIT License
A plugin for the Karma test runner that loads .html and .json fixtures
License: MIT License
According to the docs, there's a fixtures.clear()
method, but it's actually called fixtures.cleanup()
. Can you please update the docs?
Hi,
I'm trying to implement the karma fixture plugin for the first time into my angular 1 project.
Versions from package.json that are relevant:
When I follow the guide and implement everything I'm getting:
ReferenceError: Cannot find fixture '{projectpath}/test/fixtures/base/path/test1.json' in http://localhost:9876/__karma__{projectpath}/node_modules/karma-fixture/lib/fixture.js (line 141)
My folder structure for my test framework is
test - fixtures - base - path - json - test1.json
Which I followed the guide just to implement but as I said I'm getting the error above when I run the tests. Obviously the path I'm running is correct from following my directory structure. Any help would be much appreciated.
Thanks,
Garry
Unable to build as I receive this warning. One note, which I assume is unrelated, is that I only deviate from the docs in that I'm using "karma-ng-html2js-preprocessor" instead of "karma-html2js-preprocessor". But again, based on the error I don't see how this relates.
There is an issue to use karma-json-fixtures-preprocessor as a preprocessor. karma-json-fixtures-preprocessor
removes the json
extension from file.path
by default, which is needed to detect json
files by karma-fixture
https://github.com/billtrik/karma-fixture/blob/master/src/fixture.coffee#L49
There is already an pull request at karma-json-fixtures-preprocessor
aaronabramov/karma-json-fixtures-preprocessor#3
It's common to use <script>
tags as placeholders for templates, such as:
<script id="entry-template" type="text/x-handlebars-template">
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{body}}
</div>
</div>
</script>
In this case, karma-fixture throws an error because it tries to eval()
the innerText
of the <script>
node. However, browsers won't evaluate the contents of <script>
if an unknown content-type is used, so this extra step isn't necessary and actually causes problems. Is it possible to make this eval()
conditional on there being a proper content-type?
Also: innerText
doesn't work at all in Firefox. It would probably be best to use innerText || textContent
.
Hi. Pulling my hair out as usual, trying to load fixtures in Karma using Jasmine, Babel and Webpack
This is my folder structure
karma.config.js
test
├── fixtures
│ └── basic.html
└── specs
└── xxx.spec.js
This is my Jasmine test
it("doesn't work", () => {
fixture.setBase("/base/test/fixtures");
console.log('+++++++', fixture.load('basic.html'))
});
I get error: ReferenceError: Cannot find fixture 'test/fixtures/basic.html'
Window.__karma__.files
has an entry for /base/test/fixtures/basic.html whose value is an hash.
Looking at the plugin source, I see the code is looking for the fixture in a global __html__
object, which doesn't exist https://github.com/billtrik/karma-fixture/blob/master/src/fixture.coffee#L63-L66
What part of the code is responsible for creating that object and populating it? Why doesn't it exist?
Here's karma.config.js
module.exports = function(config) {
config.set({
basePath: '',
files: [
// serve assets and stylings
{ pattern: 'test/fixtures/**/*.*', watched: false, included: false, served: true },
// webpack's entry point over tests
{ pattern: 'test/specs/**/*.spec.js', watched: true, included: true, served: true }
],
// for serving JSON fixtures, see
// https://www.npmjs.com/package/karma-fixture
jsonFixturesPreprocessor: {
variableName: '__json__'
},
preprocessors: {
'test/fixtures/**/*.html': ['html2js'],
'test/fixtures/**/*.json': ['json_fixtures'],
//preprocess with webpack and sourcemap
'test/**/*.js': ['webpack', 'sourcemap']
},
webpack: {
devtool: 'inline-source-map',
module: {
loaders: [
{
test: /\.js/,
exclude: /node_modules/,
loader: "babel-loader",
query: {
presets: ["es2015"]
}
}
]
}
},
babelPreprocessor: {
options: {
presets: ['es2015'],
sourceMap: 'inline'
},
filename: function (file) {
return file.originalPath.replace(/\.js$/, '.es5.js');
},
sourceFileName: function (file) {
return file.originalPath;
}
},
frameworks: ['jasmine', 'fixture'],
singleRun: false,
browsers: ['PhantomJS'],
// enable console log within test
options: {
client: {
captureConsole: true
}
}
});
};
When run npm install, got
Done. Phantomjs binary available at C:\Users\rhan\workspace\karma-fixture\node_modules\phantomjs\lib\phantom\phantomjs.exe
[email protected] prepublish C:\Users\rhan\workspace\karma-fixture
coffee -o lib -c src/*.coffee
File not found: C:\Users\rhan\workspace\karma-fixture\src*.coffee
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN [email protected] requires a peer of mocha@* but none was installed.
npm WARN [email protected] requires a peer of chai@* but none was installed.
npm ERR! Windows_NT 6.1.7601
npm ERR! argv "C:\Users\rhan\dev\node.exe" "C:\Users\rhan\dev\node_modules\npm\bin\npm-cli.js" "install"
npm ERR! node v6.10.2
npm ERR! npm v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! [email protected] prepublish: coffee -o lib -c src/*.coffee
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] prepublish script 'coffee -o lib -c src/*.coffee'.
I just found a bug in my code caused by this unexpected behavior of fixture.load
:
let fixtureObj = fixture.load('myfixture.json')
console.log(fixtureObj.testVal) // -> prints "undefined" (which is expected)
fixtureObj.testVal = 'foo'
fixtureObj = fixture.load('myfixture.json')
console.log(fixtureObj.testVal) // -> prints "foo" (which is not expected)
It seems that fixture.load
returns the same instance of the object on each call, and thus subsequent calls will see any mutations on the object.
Would it be possible to deep clone the object before returning it via fixture.load
? This would eliminate the issues I've seen.
I am getting the following :- Cannot find fixture 'fixtures/div-foo.html'
query
text()
× "before each" hook for "should return 'foo'"
HeadlessChrome 75.0.3770 (Windows 10.0.0)
Firefox 67.0.0 (Windows 10.0.0)
Cannot find fixture 'fixtures/div-foo.html'
Fixture.prototype._throwNoFixture@node_modules/karma-fixture/lib/fixture.js:141:13
Fixture.prototype.load@node_modules/karma-fixture/lib/fixture.js:78:18
@test/main.test.js:30:25
when I code :-
describe('query', function () {
describe('text()', function () {
var div;
before(function() {
fixture.setBase('fixtures')
});
beforeEach(function() {
fixture.load('div-foo.html');
});
afterEach(function(){
fixture.cleanup()
});
/*
beforeEach(function() {
div = document.createElement('div');
div.innerText = 'foo';
div.setAttribute('id', 'foo');
document.body.appendChild(div);
});
afterEach(function() {
document.body.removeChild(div);
});
*/
describe("$('#foo').text()", function () {
it("should return 'foo'", function () {
expect($('#foo').text()).to.be.equal('foo');
});
});
describe("$('#foo').text('bar')", function () {
it("should allow $('foo').text() == 'bar'", function () {
$('#foo').text('bar');
expect(div.innerText).to.be.equal('bar');
});
});
});
When i try to load a json file with: jsonFix = fixture.load('fix.json');
i get this error:
Uncaught SyntaxError: Unexpected token :
The file is the following:
{
"test": "ok"
}
This is my configuration, i installed karma-fixture and both preprocessors.
config.set({
basePath: '..',
frameworks: ['mocha', 'sinon-chai', 'fixture'],
plugins: [
'karma-fixture',
'karma-html2js-preprocessor',
'karma-json-fixtures-preprocessor'
],
preprocessors: {
'test/fixtures/*.html': ['html2js'],
'test/fixtures/*.json': ['json_fixtures']
},
jsonFixturesPreprocessor: {
variableName: '__json__'
},
files: [
{
pattern: 'test/fixtures/**',
},
],
//...
What am i doing wrong?
I have a beforeEach
that loads a fixture and then several it
statements that use that data to create a model.
The logic i'm testing modifies the mock data object that's created by the fixture load and i've noticed that this modification persists from one it
to the next. I've tried using cleanup()
in an afterEach
but it makes no difference.
I'm presuming that once the json fixture is loaded it's cached as an object and that same objects is returned. So any modification to that object then persists. Unless i'm doing something wrong?
describe('my test', function() {
var mockData;
function changeSomeValueToB(data) {
data.someValue = 'B';
}
beforeEach(function() {
mockData = fixture.load('my/mock/data.fixture.json');
});
afterEach(function() {
fixture.cleanUp();
});
it('should do something', function() {
expect(mockData.someValue).toBe('A'); // passes
changeSomeValueToB(mockData);
});
it('should do something else', function() {
expect(mockData.someValue).toBe('A'); // fails
expect(mockData.someValue).toBe('B'); // passes
});
});
I'm currently being bitten by an error that I've tracked down to fixture.load()
not finding the file I requested. It looks like missing files are simply ignore and replace as an empty string (https://github.com/billtrik/karma-fixture/blob/master/src/fixture.coffee#L22), which makes it very hard to figure out what's going on.
Would you be open to throwing an error in that case?
This is my folder structure. Each fixture has a top level div with a classname reflecting the name of the html file.
karma.config.js
test
├── fixtures
│ ├── basic.html
│ └── complex.html
└── specs
└── xxx.spec.js
Running this test
define("testing basic", () => {
beforeEach(() => { fixture.load('basic.html'); });
afterEach=(() => { fixture.cleanup(); }); // shouldn't be needed, but hey
it("has loaded basic", () => {
expect(document.querySelector('.basic')).not.toBeNull();
expect(document.querySelector('.complex')).toBeNull();
})
define("testing complex", () => {
beforeEach(() => { fixture.load('complex.html'); });
afterEach=(() => { fixture.cleanup(); }); // shouldn't be needed, but hey
it("has loaded complex", () => {
expect(document.querySelector('.basic')).toBeNull();
expect(document.querySelector('.complex')).not.toBeNull();
});
Gives Expected null not to be null.
If I remove the second "define" block and leave
define("testing basic", () => {
beforeEach(() => { fixture.load('basic.html'); });
afterEach*=(() => { fixture.cleanup(); }); // shouldn't be needed, but hey
it("has loaded basic", () => {
expect(document.querySelector('.basic')).not.toBeNull();
expect(document.querySelector('.complex')).toBeNull();
});
Then it runs. If I console log the content of windows.fixture.el it shows that in both cases it is ".complex". I.e., loading multiple fixtures doesn't work properly with this setup.
Here's karma.config.js
module.exports = function(config) {
config.set({
basePath: '',
files: [
// serve assets and stylings
{ pattern: 'test/fixtures/**/*.*', watched: false, included: true, served: true },
// webpack's entry point over tests
{ pattern: 'test/specs/**/*.spec.js', watched: true, included: true, served: true }
],
// for serving JSON fixtures, see
// https://www.npmjs.com/package/karma-fixture
jsonFixturesPreprocessor: {
variableName: '__json__'
},
preprocessors: {
'test/fixtures/**/*.html': ['html2js'],
'test/fixtures/**/*.json': ['json_fixtures'],
//preprocess with webpack and sourcemap
'test/**/*.js': ['webpack', 'sourcemap']
},
webpack: {
devtool: 'inline-source-map',
module: {
loaders: [
{
test: /\.js/,
exclude: /node_modules/,
loader: "babel-loader",
query: {
presets: ["es2015"]
}
}
]
}
},
babelPreprocessor: {
options: {
presets: ['es2015'],
sourceMap: 'inline'
},
filename: function (file) {
return file.originalPath.replace(/\.js$/, '.es5.js');
},
sourceFileName: function (file) {
return file.originalPath;
}
},
frameworks: ['jasmine', 'fixture'],
singleRun: false,
browsers: ['PhantomJS'],
// enable console log within test
options: {
client: {
captureConsole: true
}
}
});
};
I'm getting this error when putting fixture
in my karma frameworks and running the tests.
> ./node_modules/karma/bin/karma start
INFO [karma]: Karma v0.12.16 server started at http://localhost:9876/
INFO [launcher]: Starting browser PhantomJS
INFO [PhantomJS 1.9.7 (Linux)]: Connected on socket yGSejLEmeS9OHiH1hTUP with id 85499202
PhantomJS 1.9.7 (Linux) ERROR
ReferenceError: Can't find variable: Fixture
at /home/nik/src/dmt/node_modules/karma-fixture/lib/adapter.js:3
PhantomJS 1.9.7 (Linux): Executed 0 of 0 ERROR (0.055 secs / 0 secs)
Hi
I was looking for a way to use my complex JSON file to test my responses then I found this karma-fixture project. However, it doesn't work the installation process that you put in your README. I wonder someone can help me to find my mistake or the bug in the way is included.
$ grunt jshint:test
Running "jshint:test" (jshint) task
test/spec/controllers/main.js
line 17 col 20 'fixture' is not defined.
line 28 col 9 'fixture' is not defined.
Here is my Karma.conf.js file
module.exports = function(config) {
'use strict';
config.set({
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// base path, that will be used to resolve files and exclude
basePath: '../',
preprocessors: {
"test/json/*.json" : ["json_fixtures"]
},
jsonFixturesPreprocessor: {
variableName: "__json__"
},
// testing framework to use (jasmine/mocha/qunit/...)
// as well as any additional frameworks (requirejs/chai/sinon/...)
frameworks: [
"fixture",
"jasmine"
],
// list of files / patterns to load in the browser
files: [
// bower:js
...
// endbower
"app/scripts/**/*.js",
"test/mock/**/*.js",
"test/spec/**/*.js",
{
pattern: 'test/json/*',
}
],
// list of files / patterns to exclude
exclude: [
],
// web server port
port: 8080,
...
browsers: [
"PhantomJS"
],
// Which plugins to enable
plugins: [
'karma-fixture',
'karma-json-fixtures-preprocessor',
"karma-phantomjs-launcher",
"karma-jasmine"
],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
colors: true,
logLevel: config.LOG_INFO,
});
};
and here is my test file
'use strict';
describe('Controller: MainCtrl', function () {
...
// Initialize the controller and a mock scope
beforeEach(inject(function (_$httpBackend_, _$controller_, $rootScope) {
$httpBackend = _$httpBackend_;
$controller = _$controller_;
scope = $rootScope;
jsonData = fixture.load('posts.json');
$httpBackend.whenGET('test/json/posts.json')
.respond(200,{data: jsonData});
createController = function(){
return $controller('MainCtrl', { $scope: $rootScope });
};
}));
afterEach(function () {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
fixture.cleanup();
});
...
Hi all,
Is it possible to evaluate JavaScript when I specify it via the 'src' attribute instead of directly inside <script>...</script>
? E.g. I'd like to execute
<!DOCTYPE html>
<script src="tested_code.js"></script>
and access the DOM elements created in the above script in a later test.
Thanks
Currently, on version 0.2.3, when loading a json fixture that contains an escaped character, it will not load the fixture and returns an empty array.
For example, loading myFixtureBroken.json
:
{ "myLink":"<a href=\"link.url\">Link</a>"}
returns Array[0].
This can be worked around by escaping the escapes though:
{ "myLink":"<a href=\\\"link.url\\\">Link</a>"}
It will load the object fine.
I noticed that the cleanup()
method simply empties the fixture.el
element. Wouldn't it make more sense to create a completely new container instead? In my case, the fixture container ends up with some state data that I don't want to remain for the rest of the tests.
I changed this line to this:
return this.el = document.createElement('div')
And it seems to work great. I don't see a reason to share the fixture container between tests.
I found your cool plugin for karma and it works! so thanks ...really.
Now i just would like to use fixture.setBase()
on main global karma script....not in every spec files.
I have tried but without any success.
any advise?
The 'spec/fixtures' base path is actually hardcoded into the karma plugin.
On the adapter.js there is a call to Fixture "constructor" without paramters which makes it always use the 'spec/fixtures' as the prefix for all the paths of my fixtures (on the retrieval).
This requires that you save the files in a specific place under the karama base path (spec/fixtures).
On retrieval it checks for html["" + this.base + "/" + filename]
It would be nice to have the base path be configured from a parameter. or just remove this hardcoded prefix.
Thanks in advance.
I was caught off-guard by some tests randomly failing. I tracked it down to the follow sequence:
fixtures.set
)The second test was failing because the fixture from the first test was still there. Would it make sense to auto-cleanup the fixtures in a beforeEach
? I can of course manually do this in my test case but it seems it would be nice if karma-fixture had that cleanup built-in.
If there is interest I can investigate how to do this. But before I spent any time on it I wanted to see IF adding that auto-cleanup is desirable.
Is there a way to modify the base path used for finding fixtures? My project doesn't use specs/fixtures
, and it would be hard to switch. It looks like this should be modifiable (https://github.com/billtrik/karma-fixture/blob/master/src/fixture.coffee#L3), it just seems that the option is not passed from anywhere.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.