角间谍在不支持存根模拟

时间:2019-01-07 06:54:18

标签: angular jasmine karma-jasmine angular-unit-test

我有angular 4应用程序,我正在使用jasmin + Karma编写测试用例

我的第一个测试用例在创建组件和服务实例时工作正常,

但是第二个测试用例失败了,因为当我记录其值未定义时,它无法为“ getorders”方法获取模拟数据。

    beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [ OrderListComponent ],
          providers: [
            OrderFormFetchService,
          ],
          imports: [
            BrowserModule,
            BrowserAnimationsModule,
            FormsModule,
            ReactiveFormsModule,
            HttpClientModule,
            RouterModule.forRoot([]),
            NglModule.forRoot({svgPath: 'assets/icons'}),
          LayoutModule,
          NgbModule.forRoot()
        ],
        })
        .compileComponents();
      }));


 beforeEach(() => {
        orderFormFetchService = TestBed.get(OrderFormFetchService);
        fixture = TestBed.createComponent(OrderListComponent);
        component = fixture.componentInstance;
        orderListStub = [{
          'id': '5c18e74dd5ab9332cc473c94',
          'createdAt': '2018-12-18T12:25:49.507Z',
          'updatedAt': '2018-12-18T12:25:49.507Z',
          'name': 'apple',
          'website': 'www.apple.com',
          'secsId': ''
        }];
        spyOn(orderFormFetchService, 'getorders').and.returnValue(Observable.of(orderListStub));
        fixture.detectChanges();
      });

      it('should create', () => {
        expect(component).toBeDefined();
        expect(component).toBeTruthy();
        expect(fixture).toBeDefined();
        expect(orderFormFetchService).toBeDefined();
      });

     it('check order list ', () => {
      console.log(orderFormFetchService.getorders()); // -> undefined
      expect(component.orderList).toBeDefined();
      //  expect(component.orderList).toEqual(orderListStub);
      });

OrderListComponent中的代码如下,

export class OrderListComponent   extends BaseComponent implements OnInit {

  defaultQuery = {website: null, name: null};
  orderList: any;
  query = _.clone(this.defaultQuery);
  date: Date;

  constructor(private orderFormFetchService: OrderFormFetchService) { super(); }

  ngOnInit() {
    this.date = new Date();
    this.getOrderList();
  }

  getOrderList(): void {
    this.orderFormFetchService.getOrders()
      .subscribe((res: Response) => {
        if (_.isArray(res)) {
          this.orderList = _.orderBy(res, [order => order.name.toLowerCase()], ['asc']);
        } else {
          this.orderList = [res];
        }
      });
  }
  }

请帮助

0 个答案:

没有答案