我正在编写我的第一个Angular 6单元测试。我遵循此来源https://www.youtube.com/watch?v=lTKhB6uAmno来构建我的测试文件,但最终遇到了无法解决的错误。我在SO中找到了similar question,但不幸的是没有得到答案。请指导我解决此错误。谢谢。这是我的文件,
component.ts
import { Component } from '@angular/core';
import { InputModel } from '../model/formInput';
import { APIService } from '../service/APIService';
@Component({
selector: 'results-component',
templateUrl: './result.component.html',
styleUrls: ['./result.component.css']
})
export class ResultComponent {
constructor(private apiService: APIService) { }
sendTask(model: InputModel) {
this.apiService.getRoles(model.TaskName)
.subscribe(
res => {
console.log(res)
}, err => { console.log(err) });
}
}
service.ts
import {Injectable} from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { ApiResponse } from '../model/ApiResponse';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
@Injectable()
export class APIService{
private url:string = 'http://localhost:1/api/default';
result:ApiResponse;
private http:HttpClient;
constructor(){}
getRoles(taskName:string):Observable<ApiResponse>{
var params = this.getParams(taskName);
return this.http.get<ApiResponse>(this.url,{ params })
.pipe(
map((data:ApiResponse)=>data),
catchError((err:ApiResponse)=>throwError(err))
)
}
private getParams(taskName:string){
let param = new HttpParams().set('taskName', taskName);
return param;
}
}
component.spec.ts
import { ResultComponent } from "./result.component";
import {ComponentFixture, TestBed, inject} from '@angular/core/testing';
import { APIService } from "../service/APIService";
import { of } from "rxjs";
import { ApiResponse } from "../model/ApiResponse";
import { InputModel } from "../model/formInput";
import { HttpClientTestingModule } from "@angular/common/http/testing";
describe('ResultComponent', ()=>{
let fixture:ComponentFixture<ResultComponent>;
let component:ResultComponent;
let apiService:APIService;
let model:InputModel = new InputModel();
let mockResponse : ApiResponse=
{
code:'0',
data:{
permissionsList:[
{
orgRoles:'Edit Access TRUE',
roleType:'OPTIONAL'
}
]
},
message:'',
status:'success'
};
beforeEach(()=>{
TestBed.configureTestingModule({
imports:[HttpClientTestingModule],
declarations:[ResultComponent],
providers:[APIService]//,
//{provide:HttpClient}]
}).compileComponents();
fixture = TestBed.createComponent(ResultComponent);
component = fixture.componentInstance;
apiService=TestBed.get(APIService);
model.TaskName='Edit';
});
it('test service response', ()=>{
spyOn(apiService, 'getRoles').and.returnValue(of(mockResponse));
component.sendTask(model);
expect(apiService.getOrgRoles).toHaveBeenCalled();
});
})
如果我使用虚假服务,则单元测试工作正常。我无法在我的规格文件中找到我想念的东西。
答案 0 :(得分:1)
您可以轻松完成此操作,而无需使用public function multisalarySlippdf_mail(){
$file = 'Salary Slip';
$pdfFilePath1 = FCPATH . "uploads/".$file.".pdf";
if(file_exists($pdfFilePath1)){
unlink($pdfFilePath1);
}
$this->load->library('m_pdf');// load mpdf library
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => 'abc@gmail.com',
'smtp_pass' => 'pccpl525',
'charset' => 'iso-8859-1',
'mailtype' => 'html',
'charset' => 'utf-8',
'newline' => '\r\n',
'crlf' => '\n',
'wordwrap' => TRUE
);
$salaries = $this->report->fetchAlldata();// fetching salary data from
database using report model
foreach($salarie as $sal){
$emailid = $sal->official_email; // fetch email ids from the database
if(!empty($emailid)){
$html = $this->load->view('admin/salarySlippdf',
['salaries'=>$sal,
'workingDays'=>$working_days,
'present'=>$present,
'absent'=>$absent,'extraday'=>$extraday,],true);
}
$this->m_pdf->pdf->WriteHTML($html);
$this->m_pdf->pdf->Output($pdfFilePath1, "F");// saved file in given path
$subject = " Salary Slip";
$message = "Please Download file".' '.$emailid;
$this->load->library('email', $config);
//$this->email->clear(TRUE);
$this->email->set_newline("\r\n");
$this->email->from('xyz@gmail.com');
$this->email->to($emailid);
$this->email->subject($subject);
$this->email->message($message);
$this->email->attach($pdfFilePath1);
if($this->email->send()){
echo "send";
}
else{
show_error($this->email->print_debugger());
}unlink($pdfFilePath1);
}
}
return redirect('admin/report/salaryslipmail');
}
方法。
不是为您的服务创建spyOn
,而是在providers数组中提供该间谍对象作为服务。
spy object
我正在使用describe('Result component tests', () => {
let fixture: ComponentFixture<ResultComponent>;
let component: ResultComponent;
let apiService: APIService;
let spyApiService: jasmine.SpyObj<APIService>;
let getRolesSubject;
let mockResponse: ApiResponse =
{
code: '0',
data: {
permissionsList: [
{
orgRoles: 'Edit Access TRUE',
roleType: 'OPTIONAL'
}
]
},
message: '',
status: 'success'
};
beforeEach(async(() => {
getRolesSubject = new Subject();
spyApiService = jasmine.createSpyObj('APIService', ['getRoles']);
spyApiService.getRoles.and.returnValue(getRolesSubject.asObservable());
TestBed.configureTestingModule({
declarations: [ResultComponent],
providers: [
{provide: APIService, useValue: spyApiService},
],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents().then(() => {
fixture = TestBed.createComponent(ResultComponent);
component = fixture.componentInstance;
apiService = TestBed.get(APIService);
});
}));
it('Should invoke getRoles of api service when ...', () => {
component.sendTask(model);
getRolesSubject.next(mockResponse);
expect(apiService.getRoles).toHaveBeenCalled();
});
});
从服务中返回可观察到的值。
subject
认为在subscription方法内部几乎没有方法。现在您也可以对其进行测试。