angular - 如何在业力单元测试中调用 API post 方法并在 Angular 4 中获得响应
问题描述
我正在尝试以 Angular 4 编写业力单元测试用例,以从 post 方法获得响应。我需要来自 API 的数据来编写进一步的测试用例。我的示例代码片段如下运行,但我无法得到响应。
规格
describe('Login service : ', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
HttpClientModule,
HttpClientTestingModule
]
})
.compileComponents();
}));
afterEach(inject([HttpTestingController], (backend: HttpTestingController) => {
backend.verify();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
debugElement = fixture.debugElement.query(By.css('#userName'));
htmlElement = debugElement.nativeElement;
});
it(`should emit 'true' for 200 Ok status `, async(inject([LoginService, HttpTestingController],
(service: LoginService, backend: HttpTestingController) => {
service.login({ userName: 'CF09221601k', password: 'LK6XOMPBRkH0', BrowserInfo: 'chrome 46.0.2490.86' }).subscribe((next) => {
expect(next).toBeTruthy();
});
backend.expectOne('api/ValidateClientLogin').flush(null,
{ status: 200, statusText: 'Ok' });
})));
登录服务.ts
export class LoginService {
constructor(private httpClient: HttpClient) { }
public login(user) {
return this.httpClient.post(APPCONFIG.WEBSERVICE_URL + APIURL.ValidateClientLogin, user, {observe: 'response'});
}
}
解决方案
推荐阅读
- php - Codeigniter - 在文件夹名称更改时找不到 404 页面
- java - 在Android中动态呈现不同视图的最佳方式?
- excel - 使用引用不同工作表的交替公式填充 Excel 中的行
- download - 从 ERA-Interim 下载降雪和地表降水数据时出错
- c# - 如何将 C# 语法颜色从 Visual Studio Code 导入到 Visual Studio?
- python - 具有相同变量但范围不同的两个循环
- javascript - && 运算符未按预期工作
- apache - MacOS HighSierra - 如何告诉 Apache 使用 PHP 7.2.9 而不是 PHP 7.1.16
- ios - IOS/Objective-C/Xcode:将文本复制到剪贴板
- php - 主键上的 Laravel DB 更新适用于原始数组,但不适用于变量