angular2中的单元测试,依赖注入 [英] Unit testing in angular2, dependency injection

查看:132
本文介绍了angular2中的单元测试,依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在花了1个角的时间之后开始从2号角开始。由于没有进行太多的单元测试,因为它更多是一个侧面项目,我正在尝试至少从OK开始...我从 AngularClass (如果有区别)。

Starting out with angular 2 after spending time with angular 1. Not having unit tested this much as it's more of a side project thing, I'm trying at least start out OK... I started with the example from AngularClass if that makes a difference.

已经在 app.component.ts 中挣扎,其中包含我的导航位。模板的相关位在此处:

Struggling in app.component.ts already, which contains my navigation bits. Relevant bits of the template here:

<nav class="navbar navbar-light bg-faded">
  <div class="container">
    <div class="nav navbar-nav">
      <a class="navbar-brand" [routerLink]=" ['./'] ">Navbar</a>
      <loading class="nav-item nav-link pull-xs-right" [visible]="user === null"></loading>
  </div>
</div>
</nav>

<div class="container">
  <main>
    <router-outlet></router-outlet>
</main>
</div>

<footer>
  <hr>
  <div class="container">

</div>
</footer> 

组件本身不包含太多内容:

Component itself does not contain much:

import { Component, ViewEncapsulation } from '@angular/core';
import { AuthService } from './_services';
import { User } from './_models';
import { Loading } from './_components';

@Component({
    selector: 'app',
    encapsulation: ViewEncapsulation.None,
    template: require('./app.component.html'),
    styles: [
        require('./app.style.css')
    ]
})
export class App {
    user: User;

    constructor(private auth: AuthService) {

    }

    ngOnInit() {
        this.auth.getUser().subscribe(user =>  this.user = user);
    }
}

所有模块,组件和路由都通过应用程序自举模块。可以根据需要发布。

All modules, components and routes are bootstrapped through the App module. Can post if required.

我必须为此编写的测试使我基本上从路由器连接了所有东西(看起来如此)。首先, [routerLink]不是‘a’的本机属性。好,我解决了。然后:

The test I'm having to write for it has me hooking up basically everything from the router (so it seems). First, [routerLink] is not a native attribute of 'a'. Ok, I fix it. Then:

Error in ./App class App - inline template:3:6 caused by: No provider for Router!

因此,我连接了路由器,却发现:

So, I hook up router, only to find:

Error in ./App class App - inline template:3:6 caused by: No provider for ActivatedRoute!

我添加的内容是:

Error in ./App class App - inline template:3:6 caused by: No provider for LocationStrategy!

现在,测试看起来像:

import { inject, TestBed, async } from '@angular/core/testing';
import { AuthService } from './_services';
import { Router, RouterModule, ActivatedRoute } from '@angular/router';
import { AppModule } from './app.module';

// Load the implementations that should be tested
import { App } from './app.component';
import { Loading } from './_components';

describe('App', () => {
    // provide our implementations or mocks to the dependency injector
    beforeEach(() => TestBed.configureTestingModule({
        declarations: [App, Loading],
        imports: [RouterModule],
        providers: [
            {
                provide: Router,
                useClass: class {
                    navigate = jasmine.createSpy("navigate");
                }
            }, {
                provide: AuthService,
                useClass: class {
                    getAccount = jasmine.createSpy("getAccount");
                    isLoggedIn = jasmine.createSpy("isLoggedIn");
                }
            }, {
                provide: ActivatedRoute,
                useClass: class { }
            }
        ]
    }));

    it('should exist', async(() => {

        TestBed.compileComponents().then(() => {
            const fixture = TestBed.createComponent(App);

            // Access the dependency injected component instance
            const controller = fixture.componentInstance;

            expect(!!controller).toBe(true);
        });
    }));
});

我已经在嘲笑输入内容,这对我来说似乎是错误的。我想念什么吗?是否有一种更聪明的方式将整个应用程序加载到测试中,而不是一直都依赖于每个依赖项?

I'm already mocking the inputs, this seems wrong to me. Am I missing something? Is there a smarter way of loading the whole app on a test, instead of bolting in every single dependency, all the time?

推荐答案

要进行测试,您应该使用 RouterTestingModule 代替 RouterModule 。如果要添加路线,可以使用 withRoutes

For testing, you should use the RouterTestingModule instead of the RouterModule. If you want to add routes you can use withRoutes

imports: [
  RouterTestingModule.withRoutes(Routes) // same any normal route config
]

另请参见

  • Angular 2 unit testing components with routerLink
  • Second half of this post for an idea of mock the ActivatedRoute. Sometimes you don't want the whole routing facility when unit testing. You can just mock the route.

这篇关于angular2中的单元测试,依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆