dimanche 12 août 2018

After map array became an object

I've had array that I map through and then after tests it turned out that I got object after mapping.

It had to return an array with two instances of Site containing path, siteLink and features in it (instance of a feature which is just a string. it does have the deserialize method).

(site which gave me an idea of deserialization https://nehalist.io/working-with-models-in-angular/)

enter image description here I've next service

export class SiteService {

  API_URL = '/sites';

  constructor(
    private http: HttpClient
  ) { }

  getSites(): Observable<Site[]> {
    return this.http.get<Site[]>(this.API_URL).pipe(
      map((site: Site) => new Site().deserialize(site))
    );
  }
}

And this is my Site model

export class Site implements Deserializable {
  path: string;
  siteLink: string;
  features: Feature[];

  deserialize(input: any): this {
    Object.assign(this, input);
    this.features = input.map(feature => new Feature().deserialize(feature));
    return this;
  }
}

This is my test I try

describe('SiteService', () => {
  let injector: TestBed;
  let service: SiteService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [SiteService]
    });
    injector = getTestBed();
    service = injector.get(SiteService);
    httpMock = injector.get(HttpTestingController);
  });

  afterEach(() => {
    httpMock.verify();
  });

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

  describe('#getSites', () => {
    it('should return an Observable<Site[]>', () => {
      const dummySites = [
        {
          path: 'https://example.com/img1.img',
          siteLink: 'http://example1.com',
          features: [
            'feature 1',
            'feature 2',
            'feature 3'
          ]
        },
        {
          path: 'https://example.com/img2.img',
          siteLink: 'http://example2.com',
          features: [
            'feature 1',
            'feature 2',
            'feature 3'
          ]
        }
      ];

      service.getSites().subscribe(sites => {
        console.log(sites);
        expect(sites.length).toBe(2);

        const result = sites.map(site => new Site().deserialize(site));

        expect(sites).toEqual(result);
      });

      const req = httpMock.expectOne(`${service.API_URL}`);
      expect(req.request.method).toBe('GET');
      req.flush(dummySites);
    });
  });
});

So initially I had an array then map it and it became an object. Please help with this miracle

Aucun commentaire:

Enregistrer un commentaire