【问题标题】:Unit testing in angular2, dependency injectionangular2中的单元测试,依赖注入
【发布时间】:2017-02-07 18:50:22
【问题描述】:

在 Angular 1 上花费时间之后,从 Angular 2 开始。没有进行如此多的单元测试,因为它更像是一个附带项目的东西,我正在尝试至少开始OK...我从 @987654321 的示例开始@如果这有影响的话。

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

<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> 

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

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);
    }
}

所有模块、组件和路由都通过 App 模块引导。有需要可以发帖。

我必须为它编写的测试让我基本上连接了路由器上的所有东西(看起来如此)。首先,[routerLink] is not a native attribute of 'a'。好的,我修复它。那么:

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

于是,我挂了路由器,才发现:

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);
        });
    }));
});

我已经在模拟输入,这对我来说似乎是错误的。我错过了什么吗?有没有一种更聪明的方式来加载整个应用程序进行测试,而不是一直在每个单独的依赖项中进行螺栓连接?

【问题讨论】:

    标签: unit-testing angular angular2-testing


    【解决方案1】:

    对于测试,您应该使用RouterTestingModule 而不是RouterModule。如果要添加路线,可以使用withRoutes

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

    另见

    【讨论】:

    • 谢谢,我会阅读这些内容。到目前为止,将RouterModule 更改为RouterTestingModule 已导致:inline template:3:6 caused by: undefined is not an object (evaluating 'router.events.subscribe')
    • 没关系,我在后面傻。谢谢,您的解决方案有效:)
    • 我猜你还在用模拟的Router而不是真正的
    • 正确。我一起删除了。
    • 在(路由)内部定义了什么?
    猜你喜欢
    • 2018-03-03
    • 2021-06-19
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    相关资源
    最近更新 更多