我一直试图使用Angular2发布模拟数据。 我今天尝试了以下链接,但我没有成功。
https://www.beyondjava.net/blog/mocking-http-services-with-angular-generically/
以下链接很好,但我无法使用它
http://embed.plnkr.co/9luTng/?show=preview
在上面的链接中有 fake-backend.ts 文件,如app / _helpers / fake-backend.ts
我在app.module.ts中包含的假后端但是如何使用它?
所以我想使用如下的数据请求数据进行SignUp: -
{
"username": "string",
"firstname": "string",
"lastname": "string",
"email": "string",
"password": "string",
"authtype": "plain",
"project_license":
"projectlicense"
}

我的回复应如下所示: -
{
"message": "A verification mail has been sent to your registered mail."
}

HTML模板如下: -
<div class="modal fade" id="signup-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
<div class="modal-dialog">
<div class="loginmodal-container">
<div class="row">
<h1>Sign Up</h1><br>
<form [formGroup]="signUpForm" (ngSubmit)="onSubmit()">
<div class="col-md-6" id="firstname">
<input type="text" name="firstname" placeholder="First Name" formControlName="firstname">
</div>
<div class="col-md-6" id="lastname">
<input type="text" name="lastname" placeholder="Last Name" formControlName="lastname">
</div>
<input type="text" name="user" placeholder="Enter Username" formControlName="username">
<input type="password" name="pass" placeholder="Password" formControlName="password">
<input type="text" name="email" placeholder="Email Address" formControlName="email">
<input type="text" name="license" placeholder="Project License Key" formControlName="license">
<input logOnClick type="submit" name="login" class="login loginmodal-submit" value="Create An Account">
</form>
<div class="login-help">
<p>
By clicking Create Account you agree to our terms of services & policies.
</p>
</div>
</div>
</div>
</div>
</div>
&#13;
import { Component, ReflectiveInjector } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { UserService } from '../services/user.service';
import { AlertService } from '../services/alert.service';
import { Http, BaseRequestOptions, Response, ResponseOptions, RequestMethod, XHRBackend, RequestOptions, ConnectionBackend, Headers } from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';
import { async, fakeAsync, tick } from '@angular/core/testing';
import { fakeBackendFactory } from '../helpers/fake-backend';
@Component({
selector: 'sign-up',
templateUrl: './signup.component.html',
styleUrls: ['./signup.component.css']
})
export class SignUpComponent {
loading = false;
constructor(
private userService: UserService,
private alertService: AlertService) { }
signUpForm = new FormGroup({
firstname: new FormControl('Lexo', Validators.required),
lastname: new FormControl('Luthor', Validators.required),
username: new FormControl('lex', Validators.required),
password: new FormControl('batman123', Validators.required),
email: new FormControl('darkknight@gmail.com', Validators.required),
license: new FormControl('xyz', Validators.required)
})
// injector = ReflectiveInjector.resolveAndCreate([
// {provide: ConnectionBackend, useClass: MockBackend},
// {provide: RequestOptions, useClass: BaseRequestOptions},
// Http,
// UserService,
// ]);
//_userService = this.injector.get(UserService);
//backend:MockBackend = this.injector.get(ConnectionBackend) as MockBackend;
//backend.connections.subscribe((connection: any) => this.lastConnection = connection);
onSubmit(){
console.log("Form value", this.signUpForm.value);
this.loading = true;
this.userService.create(this.signUpForm.value).
subscribe(
data => {
console.log(data);
alert("")
},
error => {
this.alertService.error(error.body);
this.loading = false;
});
let myModal:HTMLElement = document.getElementById("signup-modal");
myModal.classList.toggle("in");
myModal.style.display = "none";
}
}
&#13;
我的SignUp服务如下: -
我不想在localStorage中存储任何东西,只是为了拥有一个 注册响应如上所述。
import { Injectable, ReflectiveInjector } from '@angular/core';
import { User } from '../models/user';
import { Http, BaseRequestOptions, Response, ResponseOptions, RequestMethod, XHRBackend, RequestOptions, ConnectionBackend, Headers } from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';
import {async, fakeAsync, tick} from '@angular/core/testing';
@Injectable()
export class UserService {
connection: MockConnection;
users = localStorage.getItem("users");
constructor(private http: Http) { }
create(userInput: User) {
let users = JSON.parse(localStorage.getItem('users'));
console.log("users", users);
console.log("userinput" ,userInput);
userInput.authtype = "authtype";
userInput.project_license = "projectlicense";
let arrayOfUsers = [];
arrayOfUsers.push(userInput);
if(users == null || users == undefined) {
localStorage.setItem('users', JSON.stringify(arrayOfUsers));
}else {
users.push(userInput);
localStorage.setItem('users', JSON.stringify(users));
}
return this.http.post('/api/users', userInput, this.jwt()).map((response: Response) => response.json());
}
// private helper methods
private jwt() {
// create authorization header with jwt token
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
if (currentUser && currentUser.token) {
let headers = new Headers({ 'Authorization': 'Bearer ' + currentUser.token });
return new RequestOptions({ headers: headers });
}
}
}
&#13;
答案 0 :(得分:0)
有一种角度可用的spyon机制,您可以使用它。
以下是模拟它们需要遵循的步骤。
将服务,组件,指令注入角度测试的试验台。
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
HttpModule,
ReactiveFormsModule
],
declarations: [
SomeComponent,
GenericViewComponent
],
providers: [
SomeService, // --> this service will be mocked by spyon
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SomeComponent);
component = fixture.componentInstance;
});
现在,当你的SomeService
被注入你的试验床时,你可以在每个之前在另一个服务中模拟该服务
let someServiceApi = fixture.debugElement.injector.get(SomeService);
spyOn(someServiceApi, 'methodtomockfrom-someservice')
.and.returnValue(Observable.of({status: 'okey'});