admin管理员组

文章数量:1134247

I'm unit testing one of my directives (angularjs) using grunt/karma/phantomjs/jasmine. My tests run fine

describe('bar foo', function () {
    beforeEach(inject(function ($rootScope, $compile) {
        elm = angular.element('<img bar-foo src="img1.png"/>');
        scope = $rootScope.$new();
        $compile(elm)();
        scope.$digest();
    }));
    ....
});

but I do get these 404s

WARN [web-server]: 404: /img1.png
WARN [web-server]: 404: /img2.png
...

Although they do nothing, they do add noise to the log output. Is there a way to fix this ? (without changing karma's logLevel of course, because I do want to see them)

I'm unit testing one of my directives (angularjs) using grunt/karma/phantomjs/jasmine. My tests run fine

describe('bar foo', function () {
    beforeEach(inject(function ($rootScope, $compile) {
        elm = angular.element('<img bar-foo src="img1.png"/>');
        scope = $rootScope.$new();
        $compile(elm)();
        scope.$digest();
    }));
    ....
});

but I do get these 404s

WARN [web-server]: 404: /img1.png
WARN [web-server]: 404: /img2.png
...

Although they do nothing, they do add noise to the log output. Is there a way to fix this ? (without changing karma's logLevel of course, because I do want to see them)

Share Improve this question asked Jan 11, 2014 at 20:50 Jeanluca ScaljeriJeanluca Scaljeri 29.1k65 gold badges230 silver badges375 bronze badges 4
  • Does it persist in a different browser? I know there are some known issues with 404 errors for these types of calls in FF. – Nicholas Hazel Commented Jan 11, 2014 at 20:55
  • it has to be phantomjs. I checked Chrome which shows the 404 too. Note that they are warnings, not errors! – Jeanluca Scaljeri Commented Jan 12, 2014 at 16:03
  • Does using ng-src help? – Eitan Peer Commented Jan 13, 2014 at 9:35
  • nice try, but has the same result – Jeanluca Scaljeri Commented Jan 13, 2014 at 12:24
Add a comment  | 

9 Answers 9

Reset to default 111

That is because you need to configurate karma to load then serve them when requested ;)

In your karma.conf.js file you should already have defined files and/or patterns like :

// list of files / patterns to load in the browser
files : [
  {pattern: 'app/lib/angular.js', watched: true, included: true, served: true},
  {pattern: 'app/lib/angular-*.js', watched: true, included: true, served: true},
  {pattern: 'app/lib/**/*.js', watched: true, included: true, served: true},
  {pattern: 'app/js/**/*.js', watched: true, included: true, served: true},
  // add the line below with the correct path pattern for your case
  {pattern: 'path/to/**/*.png', watched: false, included: false, served: true},
  // important: notice that "included" must be false to avoid errors
  // otherwise Karma will include them as scripts
  {pattern: 'test/lib/**/*.js', watched: true, included: true, served: true},
  {pattern: 'test/unit/**/*.js', watched: true, included: true, served: true},
],

// list of files to exclude
exclude: [

],

// ...

You can have a look here for more info :)

EDIT : If you use a nodejs web-server to run your app, you can add this to karma.conf.js :

proxies: {
  '/path/to/img/': 'http://localhost:8000/path/to/img/'
},

EDIT2 : If you don't use or want to use another server you can define a local proxy but as Karma doesn't provide access to port in use, dynamically, if karma starts on another port than 9876 (default), you will still get those annoying 404...

proxies =  {
  '/images/': '/base/images/'
};

Related issue : https://github.com/karma-runner/karma/issues/872

The confusing piece of the puzzle for me was the 'base' virtual folder. If you don't know that needs to be included in the asset paths of your fixtures you will find it hard to debug.

As-per the configuration documentation

By default all assets are served at http://localhost:[PORT]/base/

Note: this may not be true for other versions - I'm on 0.12.14 and it worked for me but the 0.10 docs dont mention it.

After specifying the files pattern:

{ pattern: 'Test/images/*.gif', watched: false, included: false, served: true, nocache: false },

I could use this in my fixture:

<img src="base/Test/images/myimage.gif" />

And I didn't need the proxy at that point.

You can create generic middleware inside your karma.conf.js - bit over the top but did the job for me

First define dummy 1px images (I've used base64):

const DUMMIES = {
  png: {
    base64: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
    type: 'image/png'
  },
  jpg: {
    base64: 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAABAAEDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD3+iiigD//2Q==',
    type: 'image/jpeg'
  },
  gif: {
    base64: 'data:image/gif;base64,R0lGODlhAQABAAAAACwAAAAAAQABAAA=',
    type: 'image/gif'
  }
};

Then define middleware function:

function surpassImage404sMiddleware(req, res, next) {
  const imageExt = req.url.split('.').pop();
  const dummy = DUMMIES[imageExt];

  if (dummy) {
    // Table of files to ignore
    const imgPaths = ['/another-cat-image.png'];
    const isFakeImage = imgPaths.indexOf(req.url) !== -1;

    // URL to ignore
    const isCMSImage = req.url.indexOf('/cms/images/') !== -1;

    if (isFakeImage || isCMSImage) {
      const img = Buffer.from(dummy.base64, 'base64');
      res.writeHead(200, {
        'Content-Type': dummy.type,
        'Content-Length': img.length
      });
      return res.end(img);
    }
  }
  next();
}

Apply middleware in your karma conf

{
    basePath: '',
    frameworks: ['jasmine', '@angular/cli'],
    middleware: ['surpassImage404sMiddleware'],
    plugins: [
      ...
      {'middleware:surpassImage404sMiddleware': ['value', surpassImage404sMiddleware]}
    ],
    ...
}

Based on @glepretre's answer, I've created an empty .png file and added this to the config to hide 404 warnings:

proxies: {
  '/img/generic.png': 'test/assets/img/generic.png'
}

Even though its an old thread, it took me a couple hours to actually get my image to actually be served from karma to eliminate the 404. The comments were just not thorough enough. I believe I can clarify the solution with this screenshot. Essentially the one thing that many comments were missing is the fact that the proxy value must start with "/base", even though base is not in any of my folder pathing, nor is it in my requests.

("base" without the forward slash resulted in karma returning a 400 BAD REQUEST)

Now after running ng test, I can successfully serve "./src/assets/favicon.png" from the url: http://localhost:9876/test/dummy.png

In my project I am using the following npm package versions:

  • karma v4.3.0
  • jasmine-core v3.2.1
  • karma-jasmine v1.1.2
  • @angular/cli v8.3.5
  • angular v8.2.7

To fix, in your karma.conf.js make sure to point to the served file with your proxies:

files: [
  { pattern: './src/img/fake.jpg', watched: false, included: false, served: true },
],
proxies: {
  '/image.jpg': '/base/src/img/fake.jpg',
  '/fake-avatar': '/base/src/img/fake.jpg',
  '/folder/0x500.jpg': '/base/src/img/fake.jpg',
  '/undefined': '/base/src/img/fake.jpg'
}

If you are using fake URLs for your images in test, you can write a custom middleware function to return 200 for URLs that start with "$", taken from Angular's own karma.conf.js:

karma.conf.js

module.exports = function (config) {
  config.set({
    middleware: ['fake-url'],
    plugins: [
      // ...
      {
        'middleware:fake-url': [
          'factory',
          function () {
            // Middleware that avoids triggering 404s during tests that need to reference
            // image paths. Assumes that the image path will start with `/$`.
            // Credit: https://github.com/angular/components/blob/59002e1649123922df3532f4be78c485a73c5bc1/test/karma.conf.js
            return function (request, response, next) {
              if (request.url.indexOf('/$') === 0) {
                response.writeHead(200);
                return response.end();
              }

              next();
            };
          },
        ],
      },
    ]
  });
}

foo.spec.ts

img.src = '/$/foo.jpg'; // No 404 warning! :-)

If you have root path somewhere in your configuration file you can also use something like this:

proxies: {
  '/bower_components/': config.root + '/client/bower_components/'
}

I ran into a similar issue today - and while not the cleanest solution, I simply changed my test to not require a file from the local webserver.

i.e., instead of

elm = angular.element('<img bar-foo src="img1.png"/>');

I've changed my code to use

elm = angular.element('<img bar-foo src="https://example.com/img1.png"/>');

The warnings reported by Karma are from the built-in webserver, so if the file is not requested from there, no warnings are shown either.

本文标签: javascripthow to fix 404 warnings for images during karma unit testingStack Overflow