【问题标题】:Angular 2 : jasmin test case for activateRoute.snapshot.queryParams[""]Angular 2:activatedRoute.snapshot.queryParams[""] 的 jasmine 测试用例
【发布时间】:2018-01-22 03:31:18
【问题描述】:

我正在使用 ActiveRoute 从 url 读取一些值。

http://localhost:4200/project-test/#/add?orderId=156&customerNumber=431

我有单独的组件来读取 ngOnInit() 方法中的值。

sn-p:

...

constructor(private activatedRoute: ActivatedRoute,
          public sanitizer: DomSanitizer,
          private customerAPIService : CustomerAPIService) {}

ngOnInit() {

   this.orderId = this.activatedRoute.snapshot.queryParams["orderId"];
   ...
}

测试用例:

import { TestBed } from '@angular/core/testing';
import { CreateCustomer } from './create-customer.component';
import { ActivatedRoute } from '@angular/router';
import { CustomerAPIService } from "app/repackaging/service/customer.api.service";

describe('CreateCustomer', () => {
  let component;

  let mockActiveRoute;
  let mockCustomerAPIService;
  let mockQueryParamMap;

  beforeEach(() => {

     mockQueryParamMap = jasmine.createSpyObj('mockQueryParamMap', ['queryParams']);
     mockActiveRoute = {queryParamMap: mockQueryParamMap};

    TestBed.configureTestingModule({
        providers : [
           {
              provide: ActivatedRoute,
              useFactory: () => mockActiveRoute
           },
           {
              provide: CustomerAPIService,
              userFactory: () => mockCustomerAPIService
           }
      ],
      declarations :[
          CreateCustomer
      ]
    });

        component = TestBed.createComponent(CreateCustomer).componentInstance;
    });

    it('should run ngOninit function', function () {
       component.ngOnInit();

       ...

    });
});

我在编写测试时遇到错误

TypeError: undefined is not an object (evaluate 'this.activatedRoute.snapshot.queryParams') in http://localhost:9876/_karma_webpack_/main.bundle.js(第 350 行)

【问题讨论】:

  • this.activatedRoute.snapshot.queryParams 当您的mockActivatedRoute 没有snapshot 属性时,您希望如何访问它。 mockActivatedRoute 被注入为 ActivatedRoute
  • @peeskillet 同意。我们需要为快照创建单独的间谍吗?如何添加用于模拟的快照?
  • 为什么是queryParamMap?你需要一个snapshot 属性,而它又拥有自己的queryParams 属性

标签: angular typescript jasmine


【解决方案1】:

扩展@peeskillet 答案。

有一个愚蠢的错误,比如我在模拟 queryParamMap 而不是 snapshot.queryparams。

http://localhost:4200/project-test/#/add?order=156&customerNumber=431

下面是模拟activeroutes.snapshot.queryparams["order"]的解决方案。

 let orderId; 
 let customerNumber;

 let mockActiveRoute;
 ...

 beforeEach(() => {
    ...

    mockActiveRoute = {
      snapshot: {
        queryParams: {
          order: orderId,
          customerNumber: customerNumber
        }
      }
   };
});

【讨论】:

  • 如何更改另一个测试用例的“mockActiveRoute”内容,以检查不同的 orderId?
  • let route = TestBed.get(ActivatedRoute) 然后你可以更新返回值。 route 将是依赖注入容器中的单例。
猜你喜欢
  • 1970-01-01
  • 2017-08-17
  • 1970-01-01
  • 2017-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-01
  • 2017-05-01
相关资源
最近更新 更多