如何在具有分配的组件中测试可观察的服务

时间:2019-12-12 05:30:21

标签: javascript angular unit-testing

我有一个订阅服务中可观察对象的组件。然后,一旦订阅解决,我便将获得的值分配给组件属性。有什么合适的方法来测试这一点?

组件

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

# load Image as Grayscale
i = Image.open("QWiTL.png").convert("L")
# convert to numpy array
n = np.array(i)

# average columns and rows
# left to right
cols = n.mean(axis=0)
# bottom to top
rows = n.mean(axis=1)

# plot histograms
f, ax = plt.subplots(2, 1)
ax[0].plot(cols)
ax[1].plot(rows)
f.show()

单元测试

import { ANIMATIONS } from './../../helpers/animations';
import { Component, Input } from '@angular/core';
import { RickMortyService, ICharacter } from '../../services/rick-morty.service';

@Component({
    // tslint:disable-next-line:component-selector
    selector: 'character-details',
    templateUrl: './character-details.component.html',
    styleUrls: ['./character-details.component.scss'],
    animations: [
        ANIMATIONS.fade,
        ANIMATIONS.scaleUpEnter
    ]
})
export class CharacterDetailsComponent {
    @Input() character: ICharacter;
    requestLoading: boolean;

    constructor(private rickMortyService: RickMortyService) { }

    getEpisodeCharacters() {
        this.requestLoading = true;
        this.rickMortyService.getEpisodeCharacters(this.character.episode[0].id).subscribe(characters => {
            this.character.episode[0].characters = characters;
            this.requestLoading = false;
        });
    }
}

还应注意,我正在使用Apollo来获取必要的数据。在服务本身中进行了测试。

2 个答案:

答案 0 :(得分:1)

您将必须模拟getEpisodeCharacters方法并从中返回一个可观察对象,然后您可以检查从getEpisodeCharacters方法返回的模拟值是否已在this.character.episode [0] .characters中分配。像这样-

  it('should get all characters of a specific episode when calling function', async () => {
    spyOn(service, 'getEpisodeCharacters').and.returnValue(of(['test']));
    component.getEpisodeCharacters();
    expect(component.character.episode[0].characters).toEqual(['test']); // you will have to initialise component.character.episode[0] behorehand.
  });

答案 1 :(得分:0)

从rxjs导入of运算符。

import { of } from 'rxjs';


it('should get all characters of a specific episode when calling function', async () => 
 {
   spyOn(service, 'getEpisodeCharacters').and.returnValue(of(['episodeCharactersPageMock']));
   component.getEpisodeCharacters();
   expect(component.character.episode[0].characters).toEqual(['episodeCharactersPageMock']); });