N.T*_*N.T 7 unit-testing angular
当我使用flush()测试 HTTP 请求的方法时,出现此错误:
响应类型不支持自动转换为 JSON。
你能不能解释一下flush()方法的目标。我真的不明白。
问题并没有真正解决。我们必须像这样向“it”函数添加 async() 方法:“it('should get the post', async(() => {
import { TestBed } from '@angular/core/testing';
import {HttpClientTestingModule, HttpTestingController} from "@angular/common/http/testing"
import { DataService } from './data.service';
import { Observable } from 'rxjs';
import { Post } from './post.model';
import { HttpClientModule } from '@angular/common/http';
describe('DataService', () => {
let service: DataService
let httpTestingController: HttpTestingController
let attemptedPost : Post;
const post = {
userId: 1,
id: 1,
title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
body: "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
};
beforeEach(() => { TestBed.configureTestingModule({
imports : [HttpClientTestingModule,HttpClientModule],
providers : [DataService]
});
service = TestBed.get(DataService);
httpTestingController = TestBed.get(HttpTestingController)
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should get the post', () => {
service.getPosts().subscribe( (postRetrieved) => {
attemptedPost=postRetrieved;
});
const req = httpTestingController.expectOne('https://jsonplaceholder.typicode.com/posts/1');
req.flush(attemptedPost);
// expect(attemptedPost).toEqual(post);
});
});
Run Code Online (Sandbox Code Playgroud)
你的错误是该 subscribe方法是async所以你尝试这个:
service.getPosts().subscribe( (postRetrieved) => {
attemptedPost=postRetrieved;
const req = httpTestingController.expectOne('https://jsonplaceholder.typicode.com/posts/1');
req.flush(attemptedPost);
// expect(attemptedPost).toEqual(post);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5361 次 |
| 最近记录: |