Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/472.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用分配测试组件中可观察到的服务_Javascript_Angular_Unit Testing - Fatal编程技术网

Javascript 如何使用分配测试组件中可观察到的服务

Javascript 如何使用分配测试组件中可观察到的服务,javascript,angular,unit-testing,Javascript,Angular,Unit Testing,我有一个组件订阅服务中的可观察对象。然后,在解决订阅问题后,我将获得的值分配给组件属性。什么是正确的测试方法 组件 import { ANIMATIONS } from './../../helpers/animations'; import { Component, Input } from '@angular/core'; import { RickMortyService, ICharacter } from '../../services/rick-morty.service'; @C

我有一个组件订阅服务中的可观察对象。然后,在解决订阅问题后,我将获得的值分配给组件属性。什么是正确的测试方法

组件

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;
        });
    }
}

import { RickMortyService } from "src/app/services/rick-morty.service";
import { By } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { AngularFontAwesomeModule } from 'angular-font-awesome';
import { Apollo } from 'apollo-angular';
import { fakeAsync, async, ComponentFixture, TestBed, tick } from '@angular/core/testing';

import { CharacterDetailsComponent } from './character-details.component';
import { TooltipDirective } from 'src/app/directives/tooltip.directive';
import { ICharacter } from '../../services/rick-morty.service';

const mockCharacter: ICharacter = {
    id: '1',
    image: 'http://rickandmortyapi.com/api/character/avatar/1.jpeg',
    name: 'Rick Sanchez',
    status: 'Alive',
    species: 'Human',
    gender: 'Male',
    origin: {
        id: '1',
        name: 'Earth (C-137)',
        type: 'Planet',
        dimension: 'Dimension C-137'
    },
    location: {
        id: '20',
        name: 'Earth (Replacement Dimension)',
        type: 'Planet',
        dimension: 'Replacement Dimension'
    },
    episode: [
        {
            id: '31',
            air_date: 'October 1, 2017',
            name: 'The Rickchurian Mortydate',
            episode: 'S03E10'
        }
    ]
};

const episodeCharactersPageMock: ICharacter[] = [
    {
        id: '',
        image: '',
        name: 'Rick Sanchez',
        status: '',
        species: '',
        gender: '',
        origin: {
            id: '',
            name: '',
            type: '',
            dimension: ''
        },
        location: {
            id: '',
            name: '',
            type: '',
            dimension: ''
        },
        episode: []
    },
    {
        id: '',
        image: '',
        name: 'Morty Smith',
        status: '',
        species: '',
        gender: '',
        origin: {
            id: '',
            name: '',
            type: '',
            dimension: ''
        },
        location: {
            id: '',
            name: '',
            type: '',
            dimension: ''
        },
        episode: []
    }
];

describe('CharacterDetailsComponent', () => {
    let component: CharacterDetailsComponent;
    let fixture: ComponentFixture<CharacterDetailsComponent>;
    let service: RickMortyService;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [AngularFontAwesomeModule, BrowserAnimationsModule],
            declarations: [CharacterDetailsComponent, TooltipDirective],
            providers: [Apollo]
        })
            .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(CharacterDetailsComponent);
        component = fixture.componentInstance;
        component.character = mockCharacter;
        service = TestBed.get(RickMortyService);
        fixture.detectChanges();
    });

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

    it('should get all characters of a specific episode when calling function', async () => {
      // test to be written here
    });
});
单元测试

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;
        });
    }
}

import { RickMortyService } from "src/app/services/rick-morty.service";
import { By } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { AngularFontAwesomeModule } from 'angular-font-awesome';
import { Apollo } from 'apollo-angular';
import { fakeAsync, async, ComponentFixture, TestBed, tick } from '@angular/core/testing';

import { CharacterDetailsComponent } from './character-details.component';
import { TooltipDirective } from 'src/app/directives/tooltip.directive';
import { ICharacter } from '../../services/rick-morty.service';

const mockCharacter: ICharacter = {
    id: '1',
    image: 'http://rickandmortyapi.com/api/character/avatar/1.jpeg',
    name: 'Rick Sanchez',
    status: 'Alive',
    species: 'Human',
    gender: 'Male',
    origin: {
        id: '1',
        name: 'Earth (C-137)',
        type: 'Planet',
        dimension: 'Dimension C-137'
    },
    location: {
        id: '20',
        name: 'Earth (Replacement Dimension)',
        type: 'Planet',
        dimension: 'Replacement Dimension'
    },
    episode: [
        {
            id: '31',
            air_date: 'October 1, 2017',
            name: 'The Rickchurian Mortydate',
            episode: 'S03E10'
        }
    ]
};

const episodeCharactersPageMock: ICharacter[] = [
    {
        id: '',
        image: '',
        name: 'Rick Sanchez',
        status: '',
        species: '',
        gender: '',
        origin: {
            id: '',
            name: '',
            type: '',
            dimension: ''
        },
        location: {
            id: '',
            name: '',
            type: '',
            dimension: ''
        },
        episode: []
    },
    {
        id: '',
        image: '',
        name: 'Morty Smith',
        status: '',
        species: '',
        gender: '',
        origin: {
            id: '',
            name: '',
            type: '',
            dimension: ''
        },
        location: {
            id: '',
            name: '',
            type: '',
            dimension: ''
        },
        episode: []
    }
];

describe('CharacterDetailsComponent', () => {
    let component: CharacterDetailsComponent;
    let fixture: ComponentFixture<CharacterDetailsComponent>;
    let service: RickMortyService;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [AngularFontAwesomeModule, BrowserAnimationsModule],
            declarations: [CharacterDetailsComponent, TooltipDirective],
            providers: [Apollo]
        })
            .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(CharacterDetailsComponent);
        component = fixture.componentInstance;
        component.character = mockCharacter;
        service = TestBed.get(RickMortyService);
        fixture.detectChanges();
    });

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

    it('should get all characters of a specific episode when calling function', async () => {
      // test to be written here
    });
});
从“src/app/services/rick morty.service”导入{RickMortyService};
从“@angular/platform browser”导入{By}”;
从“@angular/platform browser/animations”导入{BrowserAnimationsModule};
从“AngularFontAwesomeModule”导入{AngularFontAwesomeModule};
从“Apollo angular”导入{Apollo};
从'@angular/core/testing'导入{fakeAsync,async,ComponentFixture,TestBed,tick};
从“./character details.component”导入{CharacterDetailsComponent};
从'src/app/directions/tooltip.directive'导入{TooltipDirective};
从“../../services/rick morty.service”导入{ICharacter};
常量mockCharacter:ICharacter={
id:'1',
图像:'http://rickandmortyapi.com/api/character/avatar/1.jpeg',
姓名:“瑞克·桑切斯”,
状态:“活着”,
物种:“人类”,
性别:'男性',
来源:{
id:'1',
名称:“地球(C-137)”,
类型:'行星',
尺寸:“尺寸C-137”
},
地点:{
id:'20',
名称:“接地(更换尺寸)”,
类型:'行星',
维度:“替换维度”
},
插曲:[
{
id:'31',
空运日期:2017年10月1日,
名称:'Rickchurian Mortydate',
第集:“S03E10”
}
]
};
常量epiodecharacterspagemock:ICharacter[]=[
{
id:“”,
图像:“”,
姓名:“瑞克·桑切斯”,
状态:“”,
物种:'',
性别:'',
来源:{
id:“”,
名称:“”,
类型:“”,
维度:“”
},
地点:{
id:“”,
名称:“”,
类型:“”,
维度:“”
},
插曲:[]
},
{
id:“”,
图像:“”,
姓名:“莫蒂·史密斯”,
状态:“”,
物种:'',
性别:'',
来源:{
id:“”,
名称:“”,
类型:“”,
维度:“”
},
地点:{
id:“”,
名称:“”,
类型:“”,
维度:“”
},
插曲:[]
}
];
描述('CharacterDetailsComponent',()=>{
let组件:CharacterDetails组件;
let夹具:组件夹具;
让服务:RickMortyService;
beforeach(异步(()=>{
TestBed.configureTestingModule({
导入:[AngularFontawesome模块,BrowserAnimationsModule],
声明:[CharacterDetailsComponent,TooltipDirective],
提供者:[阿波罗]
})
.compileComponents();
}));
在每个之前(()=>{
fixture=TestBed.createComponent(CharacterDetailsComponent);
组件=fixture.componentInstance;
component.character=mockCharacter;
service=TestBed.get(RickMortyService);
fixture.detectChanges();
});
它('应该创建',()=>{
expect(component.toBeTruthy();
});
它('调用函数时应获取特定事件的所有字符',async()=>{
//要在此处编写的测试
});
});

还应该注意的是,我正在使用阿波罗获得必要的数据。这是在服务本身中测试的。

您必须模拟getEpisodeCharacters方法并从中返回一个可观察值,然后您可以检查从getEpisodeCharacters方法返回的模拟值是否已分配到此.character.eption[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.
  });

从rxjs导入操作员的

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']); });