为什么在比较两个相同的对象时出现错误:'Expected PostModel({ }) to be PostModel({ }).' 在我的测试中

Why I've got an error when comparing two same object : 'Expected PostModel({ }) to be PostModel({ }).' in my test

我正在尝试测试调用 API 的 Angular 服务,并比较响应。但是之前我只是想比较没有数据的全局对象。我的这部分代码有一个错误 const resp: PostModel = service.setPost('data'); mockRequest.flush(resp); mockHttp.verify(); 而且我不理解因为对我来说它们是相同的对象。 这里是

我的post-service.ts

  public addPost(newPost: PostModel): Observable<PostModel> {
     return this.http.post(this.apiUrl + 'add', newPost).pipe( map( response => {
     console.log('response: ', response);
     return this.setPost(response);
   }));
 }


 public setPost(data: any): PostModel{
    let post: PostModel= new PostModel();
    /**
    post.id = data.id;
    post.author = data.userId;
    post.title = data.title;
    post.content = data.content;
    post.description = data.description;
    post.img.push(data.img);
    post.isHorror = !data.forChild;
    */
    return post;
  }

我的post-service.spec.ts

import {inject, TestBed} from '@angular/core/testing';
import { HttpClientModule } from '@angular/common/http';
import {HttpClientTestingModule,HttpTestingController,} from '@angular/common/http/testing';
import PostModel from '../models/Post.model';
import { PostService } from './post.service';

describe('PostService', () => {
  let mockHttp: HttpTestingController;
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientModule, HttpClientTestingModule],
      providers: [PostService]
    });
    mockHttp = TestBed.get(HttpTestingController);
  });

  it('should be created', inject( [PostService], (service: PostService) => {
    expect(service).toBeTruthy();
  }));

  it('shoul call post and return PostModel', inject(
    [PostService], (service: PostService) => {
      const newPost: PostModel = new PostModel();
      service.addPost(newPost).subscribe((response => {
        expect(response).toBe(newPost);
      }));

      const mockRequest = mockHttp.expectOne('api/story/post/add');
      expect(mockRequest.request.method).toEqual('POST');
      /** const data = this.generatePostMock(); */
      const resp: PostModel = service.setPost('data');
      mockRequest.flush(resp);
      mockHttp.verify();
    }
  ));
  
  generatePostMock(): PostModel {
    let mock: PostModel = new PostModel();
    mock.id = 1;
    mock.author = 12;
    mock.title = 'title';
    mock.content = 'content';
    mock.description = 'description';
    mock.img.push('../assets/img/hell_dog.png');
    mock.isHorror = true;
  }
});

您不是在比较同一个对象,而是比较相同的对象,因此您必须使用 toEqual(newPost) 而不是 toBe(newPost),如下所示:

expect(response).toEqual(newPost);

from Jasmine Matchers documentation:

toBe(expected): expect the actual value to be === to the expected value.

toEqual(expected): expect the actual value to be equal to the expected, using deep equality comparison.