【问题标题】:Cannot load the injected service in test无法在测试中加载注入的服务
【发布时间】:2016-04-06 17:12:13
【问题描述】:

我有一个“可注入”服务,我想对其进行基本测试:

login.service.ts

从 'angular2/core' 导入 { Injectable }; 从 'angular2/http' 导入 { Http, Response };

@Injectable()
export class LoginService {

    constructor(private http: Http) { }
    response: JSON;
    getPartners() {
        return this.http.get('http://bla/bla/partners')
                        .map((res: Response) => res.json());
    }
}

现在我的测试: login.service.spec.ts

import { it, iit, describe, expect, inject, injectAsync, beforeEachProviders, fakeAsync, tick } from 'angular2/testing';
import { provide } from 'angular2/core';
import { LoginService } from './login.service';



describe('login service', () => {
  beforeEachProviders(() => [LoginService])

  it('should get partners', inject([LoginService], (service) => {
    console.log('HERE ', service)
    expect(true).toBe(true);
    // todo expect(service.getPartners())...
  }));

由于收到 404,我还不能去任何地方: 加载资源失败:服务器响应状态为 404(未找到) http://localhost:9876/base/dist/components/login/login.service 我可能缺少一些基本的东西,因为我遇到了我需要测试但不是接口的任何类的这个问题。

我的 karma-test-shim.js:

// Tun on full stack traces in errors to help debugging
Error.stackTraceLimit = Infinity;


jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;

// // Cancel Karma's synchronous start,
// // we will call `__karma__.start()` later, once all the specs are loaded.
__karma__.loaded = function () { };


System.config({
    packages: {
        'base/src': {
            defaultExtension: false,
            format: 'register',
            map: Object.keys(window.__karma__.files).
                filter(onlyAppFiles).
                reduce(function createPathRecords(pathsMapping, appPath) {
                    // creates local module name mapping to global path with karma's fingerprint in path, e.g.:
                    // './hero.service': '/base/src/app/hero.service.js?f4523daf879cfb7310ef6242682ccf10b2041b3e'
                    var moduleName = appPath.replace(/^\/base\/src\//, './').replace(/\.js$/, '');
                    pathsMapping[moduleName] = appPath + '?' + window.__karma__.files[appPath]
                    return pathsMapping;
                }, {})

        }
    }
});

System.import('angular2/src/platform/browser/browser_adapter').then(function (browser_adapter) {
    browser_adapter.BrowserDomAdapter.makeCurrent();
}).then(function () {
    return Promise.all(
        Object.keys(window.__karma__.files) // All files served by Karma.
            .filter(onlySpecFiles)
        // .map(filePath2moduleName)        // Normalize paths to module names.
            .map(function (moduleName) {
                // loads all spec files via their global module names (e.g. 'base/src/app/hero.service.spec')
                return System.import(moduleName);
            }));
})
    .then(function () {
        __karma__.start();
    }, function (error) {
        __karma__.error(error.stack || error);
    });


function filePath2moduleName(filePath) {
    return filePath.
        replace(/^\//, '').              // remove / prefix
        replace(/\.\w+$/, '');           // remove suffix
}


function onlyAppFiles(filePath) {
    return /^\/base\/src\/.*\.js$/.test(filePath)
}


function onlySpecFiles(path) {
    return /.spec\.js$/.test(path);
}

我的 karma.conf.js:

files: [
    // paths loaded by Karma
    { pattern: 'node_modules/angular2/bundles/angular2-polyfills.js', included: true, watched: true },
    { pattern: 'node_modules/systemjs/dist/system.src.js', included: true, watched: true },
    { pattern: 'node_modules/rxjs/bundles/rx.js', included: true, watched: true },
    { pattern: 'node_modules/angular2/bundles/angular2.js', included: true, watched: true },
    { pattern: 'node_modules/angular2/bundles/testing.dev.js', included: true, watched: true },
    { pattern: 'karma-test-shim.js', included: true, watched: true },
    { pattern: 'dist/components/matchers.js', included: true, watched: true },

    // paths loaded via module imports
    { pattern: 'dist/components/**/*.js', included: false, watched: true },

    // paths loaded via Angular's component compiler
    // (these paths need to be rewritten, see proxies section)
    { pattern: 'dist/*.html', included: false, watched: true },
    { pattern: 'dist/styles/*.css', included: false, watched: true },
    { pattern: 'dist/components/**/*.html', included: false, watched: true },
    { pattern: 'dist/components/**/*.css', included: false, watched: true },

    // paths to support debugging with source maps in dev tools
    { pattern: 'src/components/**/*.ts', included: false, watched: false },
    { pattern: 'dist/components/**/*.js.map', included: false, watched: false }
],

dist 是我的构建文件夹

【问题讨论】:

  • 您能添加您的karma-test-shim.js 文件吗?我认为问题出在 SystemJS 配置级别。谢谢!
  • 谢谢!这是我的 karma-test-shim.js:
  • 你能把它放在你的问题中吗?谢谢;-)
  • 是的,我刚刚做到了!感谢收看!

标签: angular karma-jasmine


【解决方案1】:

我认为你的配置应该在karma-test-shim.js文件中如下:

System.config({
  packages: {
    'base/dist': { // <-------------
        defaultExtension: false,
        format: 'register',
        map: Object.keys(window.__karma__.files).
            filter(onlyAppFiles).
        (...)

【讨论】:

  • 也试过了,同样的错误:angular2-polyfills.js:469 Unhandled Promise reject: karma.error is not a function ;区域: ;任务:Promise.then;值:TypeError:karma.error 不是函数(…)consoleError @ angular2-polyfills.js:469 angular2-polyfills.js:471 错误:未捕获(承诺):TypeError: karma.error is not a function(...)consoleError @ angular2-polyfills.js:471 localhost:9876/base/dist/components/login/login.service 加载资源失败:服务器响应状态为 404(未找到)
  • createPathRecords方法产生了什么?我的意思是映射(模块名称/目标文件)。
  • 我认为它映射文件路径(用于 Karma)以便能够获取它们。我刚刚查看了 angular2-test-seed 应用程序,并且是同样的事情......
  • 是的,但是您可能会在路径上有细微差别,并且模块不会加载。关于您的留言,我认为 SystemJS 可以加载模块(我的意思是它可以在此地图中找到正确的路径)...
  • 我坚信你是对的。我刚刚读了这篇文章:stackoverflow.com/questions/36308616/…,我想知道我在加载模块时是否不匹配
猜你喜欢
  • 1970-01-01
  • 2020-07-27
  • 2016-05-29
  • 1970-01-01
  • 2013-04-07
  • 2016-05-11
  • 2012-08-31
  • 1970-01-01
  • 2019-05-22
相关资源
最近更新 更多