Why is Karma refusing to serve my JSON fixture (which I'd like to use in my jasmine / angularjs tests)

早过忘川 提交于 2019-11-30 22:22:46

Your problem is that 'false' has to be a boolean, not a string.

There is already an issue to validate the config better and fix such a mistakes.

Also, you might write a simple "json" preprocessor (similar to karma-html2js) that would make it valid JS and put the JSON into some global namespace so that you can keep the tests synchronous...

I also needed json fixtures in my karma test suite. I ended up just using the html2js preprocessor with json files as well as html.

karma.conf.js:

module.exports = function (config) {
  config.set({
    frameworks: ["jasmine"],
    files: [
        '**/*.js',
        '**/*.html',
        '**/*.json',
        '**/*.spec.js'
    ],
    plugins: [
        'karma-html2js-preprocessor'
    ]
    preprocessors: {
        '**/*.html': ['html2js'],
        '**/*.json': ['html2js']
    }
  });
};

Then it is just a matter of getting the json from the __html__ global.

e.g.

var exampleJson = __html__['example.json'];
var jsonObj = JSON.parse(exampleJson);
var exampleHtml = __html__['example.html'];
document.body.innerHTML = exampleHtml;

So, I had a lot of issues with jasmine-jquery and I got a pretty decent workaround.

It's a little hacky, but it works. Basically, I just create a function accessible on the window, then stack the JSON fixtures inside a little switch:

if (typeof(window.fixtures === "undefined")) {
  window.fixtures = {};
}

window.setFixture = function(type) {
  var json;

  if (type == "catalog") {
    json = { ... }
  }

if (typeof(type) !== "undefined") {
  window.fixtures[type] = json;
}
  return json;

}

Then, I can just stub it inline in the view:

describe "App.Models.Catalog", ->
  it "provides the 'App.Models.Catalog' function", ->
    expect(App.Models.Catalog).toEqual(jasmine.any(Function))

  it "sets up a fixture", ->
    setFixture("catalog")
    console.log(fixtures["catalog"])
    expect(fixtures["catalog"]).toBeDefined()

Boom, tests pass, and the object comes out in the log:

{
  catalog_id: '2212',
  merchant_id: '114',
  legacy_catalog_id: '2340',
  name: 'Sample Catalog',
  status: '1',
  description: 'Catalog Description ',
}

Now, it's accessible within my test.

It's of course not perfect or ideal, but I kept hitting strange matchErrors and the like with the jasmine-jquery plugin, and it's simple enough (and fast) for me to paste in a couple of JSON blocks and get moving.

You also save yourself the time fiddling around with the configuration and making any changes to the files for Karma.

Anyone have any better suggestions or have any luck getting jasmine-jquery to work?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!