angular 2 次测试 w/router

angular 2 testing w/router

我有一个组件,当用户登录时,它会路由到一个名为 /dashboard 的 url,我真的很难弄清楚为什么会出现以下错误。

cannot read property 'args' of undefined

我一直在关注此处找到的有关使用路由器进行测试的官方文档 https://angular.io/docs/ts/latest/guide/testing.html#!#routed-component 但它似乎没有帮助。我的一半问题是我不太理解文档中的所有代码。这是我对路线的单元测试

 beforeEach(async(()=>{

      class AuthStub{
        private loggedin: boolean = false;
            login(){
              return this.loggedin = true;

            }
      };

      class RouterStub{
        navigateByUrl(url:string){return url;}
      }

    TestBed.configureTestingModule({
      declarations: [ HomePageContentComponent ],
      providers:[
        {provide: Auth, useClass:AuthStub},
        {provide: Router, useClass: RouterStub}
        ]
    })
    .compileComponents()
  }));

  beforeEach(()=>{

      fixture = TestBed.createComponent(HomePageContentComponent);
      comp = fixture.componentInstance;

      de = fixture.debugElement.query(By.css('.loginbtn'));
      el = de.nativeElement;
      fixture.detectChanges();

    });

    it('Should log in and navigate to dashboard', inject([Router],(router:Router)=>{

      const spy = spyOn(router, 'navigateByUrl');

      el.click();

      const navArgs = spy.calls.first().args[0];

      expect(navArgs).toBe('/dashboard');

    }))      
}); 

所以我的问题是这行代码在做什么...

const navArgs = spy.calls.first().args[0];

我该如何解决我的问题?

已添加服务

@Injectable()
export class Auth { 
    lock = new Auth0Lock('fakefakefakefakefake', 'fake.auth0.com', {
         additionalSignUpFields: [{
            name: "address",                              
            placeholder: "enter your address"
        }],
        theme: {
            primaryColor:"#b3b3b3",
        },
         languageDictionary: {
            title: "FAKE"
        }
    });

    userProfile: any;

    constructor(private router: Router) {
        this.userProfile = JSON.parse(localStorage.getItem('profile'));

        this.lock.on("authenticated", (authResult) => {
            localStorage.setItem('id_token', authResult.idToken);

            this.lock.getProfile(authResult.idToken, (error, profile) => {
                if (error) {

                    alert(error);
                    return;
                }

                profile.user_metadata = profile.user_metadata || {};
                localStorage.setItem('profile', JSON.stringify(profile));
                this.userProfile = profile;
            });
            this.router.navigate(['/dashboard']);
        });
    }

    public login(){
        this.lock.show();

    };

    public authenticated() {
        return tokenNotExpired();
    };

    public logout() {
        localStorage.removeItem('id_token');
        localStorage.removeItem('profile');
        this.router.navigate(['/logout']);
    };
}

假设您有以下组件:

@Component({
  selector: 'home-comp',
  template: `<button (click)="login()" class="loginbtn">Login</button>
  `
})
export class HomePageContentComponent {
  constructor(private auth: Auth, private router: Router) { }

  login() {
    this.router.navigateByUrl(`/dashboard`);
  }
}

在您的测试中,将真实的 Router 替换为模拟版本后:

{ provide: Router, useClass: RouterStub }

在你的案例中:

it('Should log in and navigate to dashboard', inject([Router],(router:Router)=>{

router 将是 RouterStub.

的实例

然后你监视 navigateByUrl 方法来观察它被调用了多少次

const spy = spyOn(router, 'navigateByUrl');

所以当你点击 .loginbtn 按钮时 router.navigateByUrl 是 运行 (见上面的组件)并且 spy 递增 calls 一些信息(对于例如,所谓的参数)

终于在这一行

const navArgs = spy.calls.first().args[0];

预计您的 router.navigateByUrl 方法至少被调用一次,然后从第一次调用中获取传递的参数。

这里正在工作Live Example

可能你哪里出错了,你的router.navigateByUrl没有被执行。