Loading a mock JSON file within Karma+AngularJS test

前端 未结 8 1581
星月不相逢
星月不相逢 2020-11-28 18:57

I have an AngularJS app set up with tests using Karma+Jasmine. I have a function I want to test that takes a large JSON object, converts it to a format that\'s more consumab

8条回答
  •  清歌不尽
    2020-11-28 19:28

    Serving JSON via the fixture is the easiest but because of our setup we couldn't do that easily so I wrote an alternative helper function:

    Repository

    Install

    $ bower install karma-read-json --save
    
      OR
    
    $ npm install karma-read-json --save-dev
    
      OR
    
    $ yarn add karma-read-json --dev
    

    Usage

    1. Put karma-read-json.js in your Karma files. Example:

      files = [
        ...
        'bower_components/karma-read-json/karma-read-json.js',
        ...
      ]
      
    2. Make sure your JSON is being served by Karma. Example:

      files = [
        ...
        {pattern: 'json/**/*.json', included: false},
        ...
      ]
      
    3. Use the readJSON function in your tests. Example:

      var valid_respond = readJSON('json/foobar.json');
      $httpBackend.whenGET(/.*/).respond(valid_respond);
      

提交回复
热议问题