【问题标题】:Unit testing Angular Router queryParamMap单元测试 Angular 路由器 queryParamMap
【发布时间】:2022-06-23 17:24:09
【问题描述】:

我希望在 ngOnInit 生命周期中使用 Angular queryParamMap。目标是将查询参数从这个组件作为状态传递给另一个。虽然功能就像魅力一样,但我无法对代码功能进行单元测试。

export class AppComponent implements OnInit {

  constructor(private readonly route: Router, private router: ActivatedRoute) {}

  ngOnInit() {
    this.router.queryParamMap.subscribe((resp) => {
      
    const state ={} as any;
    state.token = resp.get('token')
    state.clientID = resp.get('id')
    state.timestamp = resp.get('timeStamp')
      
      this.route.navigate(['/dashboard'],{state})
    });
  }}

这是我开玩笑的单元测试方法

const activatedRouteMock = {
    queryParamMap: of(routes:{token:1,id:2},
    test(key){
return this.routes.key
})
  };



const mockRoute = mock<Router>();

当我这样做时

it('should be defined', () => {
    component.ngOnInit()
expect(mockRoute.navigate).toBeCalledTimes(1)
expect(mockRoute.navigate).toBeCalledWith(['dashboard'], {state:{token:1,id:2}})
});

但我得到错误

预期呼叫 1 已接电话 0

我不确定如何使用 QueryParamMap 对该功能进行单元测试,因为属性可能为空。

【问题讨论】:

  • 查看RouterTestingModule
  • @Antoniossss 我的问题是单元测试没有超过subscribe。我在订阅后尝试了控制台日志记录,但根本没有记录。
  • 提供完整的测试配置。不知道你的 setuo 看起来如何
  • Anwy 为什么路由是路由器而路由器是激活路由对我来说是个谜
  • 清理你的代码,提供完整的例子,不要假设你知道哪些部分对案例很重要,哪些不重要。把它全部包含进去

标签: angular typescript unit-testing jestjs url-parameters


【解决方案1】:

在我的例子中,我使用 Jest 来实现我的测试。

我的组件构造函数和 ngOnInit 方法如下所示:

constructor(private route: ActivatedRoute){}

ngOnInit(): void {
    this.route.queryParamMap.subscribe((params) => {
        this.partner = params.get('partner')
    }
}

然后在测试文件中,我创建一个带有模拟 get 函数的 params 对象,并将此设置应用于 beforeEach 方法:

const params = {
    get: jest.fn()
}

describe('MyComponent', () => {
    beforeEach(async () => {
        await TestBed.configureTestingModule({
            imports: [RouterTestingModule],
            declarations: [MyComponent],
            providers: [{
                provide: ActivatedRoute,
                useValue: {
                    queryParamMap: of(params)
                }
            }]
        })
    )

    beforeEach(() => {
        fixture = TestBed.createComponent(MyComponent)
        component = fixture.componentInstance
        fixture.detectChanges()
        TestBed.inject(ActivatedRoute)
    )
}

在我的测试用例中,我监视了我的 params 模拟对象的 get 函数,因为我在提供程序中设置为在 ActivatedRoute.queryParamMap 的可观察对象内返回此对象:

it('should set the partner property to PARTNER_X as in the GET parameter', () => {
      const getParamSpy = jest.spyOn(params, 'get').mockReturnValueOnce('PARTNER_X')
  
      component.ngOnInit()

      expect(component.partner).toBe('PARTNER_X')
      expect(getParamSpy).toBeCalledWith('partner')
})

要获得更具体的答案,最好提供有关您的设置的更多详细信息,否则很难确定您可能面临的问题。

我希望这可能有用。

【讨论】:

    猜你喜欢
    • 2013-12-24
    • 1970-01-01
    • 2018-01-15
    • 1970-01-01
    • 2015-04-01
    • 2013-04-06
    • 2020-08-15
    • 2020-03-19
    • 2017-02-09
    相关资源
    最近更新 更多