具有模拟服务的单元测试组件-错误

时间:2019-01-09 19:41:15

标签: angular unit-testing jasmine mocking spy

我开始在Angular中测试组件和服务。我观看了有关多元视野的课程,并尝试遵循以下观点:https://codecraft.tv/courses/angular/unit-testing/mocks-and-spies/ 但是,我对测试组件方法有疑问。不幸的是,我找不到解决方案,所以决定向您寻求帮助。

我的服务:

@Injectable()
export class MyService {
  private config: AppConfig;
  constructor(private apiService: ApiService, private configService: ConfigurationService) {
    this.config = configService.instant<AppConfig>();
  }

  public get(name: string, take: number = 10, skip: number = 0, params?:any): Observable<any> {
    return this.apiService.post(`${this.config.baseUrl}/${name}/paginated?take=${take}&skip=${skip}`, params);
  }
}

我的组件:

 @Component({
  selector: 'my',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.scss']
})
export class MyComponent implements OnInit {
  @Input("customerId") customerId: string;
  items: CustomerItem[] = [];

  public pagingInfo: PagingMetadata = {
    itemsPerPage: 5,
    currentPage: 1,
    totalItems: 0
  };
  constructor(private service: MyService) { }

  ngOnInit() {
    if (this.customerId) {
      this.updateItems();
    }
  }

  updateItems() {
    let skip = (this.pagingInfo.currentPage - 1) * this.pagingInfo.itemsPerPage;
    let take = this.pagingInfo.itemsPerPage;
    this.service.get("customer", take, skip, { customerId: this.customerId }).subscribe(result => {
      this.items = result.entities;
      this.pagingInfo.totalItems = result.total;
    }, (error) => {
      console.log(error.message);
    });
  }
}

我的my.component.spec.ts测试文件:

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;
  let mockService;
  let ITEMS = [
    {
        "title": "test",
        "id": "5e188d4f-5678-461b-8095-5dcffec0855a"
    },
    {
        "title": "test2",
        "id": "5e188d4f-1234-461b-8095-5dcffec0855a"
    }
]

beforeEach(async(() => {
  mockService = jasmine.createSpyObj(['get']);

  TestBed.configureTestingModule({
    imports: [NgxPaginationModule, RouterTestingModule],
    declarations: [MyComponent],
    providers: [
      { provide: MyService, useValue: mockService }
    ]
  })
    .compileComponents();
}));

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

// works fine
it('should create', () => {
  expect(component).toBeTruthy();
});

// works fine
it('should NOT call updateItems method on initialization', () => {
  component.ngOnInit();
  let spy = spyOn(component, 'updateItems').and.callThrough();

  expect(spy).not.toHaveBeenCalled();
});

// works fine
it('should call updateItems method on initialization', () => {
    component.customerId = "1";
    let spy = spyOn(component, 'updateItems').and.callFake(() => { return null });

    component.ngOnInit();

    expect(spy).toHaveBeenCalled();
  });

// gives error
it('should update items', () => {
  component.pagingInfo.currentPage = 1;
  component.pagingInfo.itemsPerPage = 10;
  component.customerId = "1";
  mockService.get.and.returnValue(of(ITEMS));

  component.updateItems();

  expect(component.items).toBe(ITEMS);
});
});

3个前一个测试工作正常,但是在最后一个-更新项目时出现错误:

  

预期未定义为[Object({“ title”:“ test”,“ id”:“ 5e188d4f-5678-461b-8095-5dcffec0855a”},{“ title”:“ test2”,“ id”:“ 5e188d4f-1234-461b-8095-5dcffec0855a“})]

对于任何提示,我将不胜感激;)

1 个答案:

答案 0 :(得分:1)

非常完整的问题,谢谢!它使我可以将它们全部放在StackBlitz中,以确保我正确地找到了您面临的问题。 :)

在该StackBlitz中,您可以看到测试全部通过了。为了使它们通过,我只做了一个更改,就更改了您从mockService.get返回的值,如下所示:

mockService.get.and.returnValue(of({entities: ITEMS, total: 2}));

原因是您的组件期望结果对象中有一个带有项目值的“实体”键。注意-它也希望也有一个“ total”键,所以我也添加了该键,尽管您没有对此进行测试。

要注意的另一件事,我在StackBlitz中进行了更改以进行演示。尽管您的测试将在编写时全部通过,但您可能不知道fixture.detectChanges()实际上执行了ngOnInit()-以前使我不胜其烦。为了说明这一点,我修改了在一个规范中您专门调用component.ngOnInit()的位置以及在此规范中您调用component.updateItems()的位置,并将其替换为fixture.detectChanges()。两者当然都可以正常工作,但是我指出这一点,因为在某些测试中,您需要先设置模拟,然后再调用ngOnInit()来获取有效数据,并将fixture.detectChanges()放入beforeEach()中首先,所有规范意味着每次调用每个规范之前都会调用它。

我希望这会有所帮助。