带路由器的角度2测试 [英] angular 2 testing w/router

查看:91
本文介绍了带路由器的角度2测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件,当用户登录时,它会路由到名为/dashboard的url,我确实在努力弄清为什么出现以下错误.

I have a component and when a user logs in it routes to a url called /dashboard I am really struggling figuring out why I am getting the following error.

cannot read property 'args' of undefined

我一直在关注有关使用路由器进行测试的官方文档,网址为

I have been following the official docs on testing with router found here https://angular.io/docs/ts/latest/guide/testing.html#!#routed-component but it doesnt seem to help. Half my problem is I dont quite understand all the code in the doc. Here is my unit test for the route

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

    }))      
}); 

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

So my question is what is this line of code doing...

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替换为模拟版本后的测试中:

In your test after replacing real Router with mocked version:

{ provide: Router, useClass: RouterStub }

在您的情况下:

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

router将是RouterStub的实例.

然后窥探navigateByUrl方法,以查看该方法被调用了多少次

then you spy on for navigateByUrl method to watching how many times it was called

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

因此,当您单击.loginbtn按钮时,router.navigateByUrl正在运行(请参见上面的组件),并且spy使用某些信息(例如,所谓的自变量)使calls递增

so when you clicking on the .loginbtn button router.navigateByUrl is running (see above component) and spy incrementes calls with some information(for example, what was called the argument)

最后一行

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

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

is expected that your router.navigateByUrl method was called at least once then is getting passed argument from the first call.

这里正在工作 实时示例

Here is working Live Example

可能您在某个地方出错了,并且您的router.navigateByUrl没有执行.

Possible you went wrong somewhere and your router.navigateByUrl isn't executed.

这篇关于带路由器的角度2测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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