Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jasmine angular2 check array length toEqual return true

Hi I am new to angular2 and just finished the heroes example. I thought it would be good to add unit test and I started with hero.service.

this is hero service

getHeroes():Promise{

return this.http.get(this.heroesUrl ).toPromise().then(response=>response.json().data as Hero[]).catch(this.handleError);

}

this is my unit test

const fakedHeroes:Hero[]=[
  { id: 1, name: 'Windstorm' },
  { id: 2, name: 'Bombasto' },
  { id: 3, name: 'Magneta' },
  { id: 4, name: 'Tornado' }
]
 describe('get Heroes test',()=>{
    let service:HeroService=null;
    let backend:MockBackend=null;
    beforeEach(inject([HeroService,MockBackend],(heroSerivce:HeroService,mockBackend:MockBackend)=>{
        service=heroSerivce;
        backend=mockBackend;
    }));
    it('get heroes',(done)=>{

        backend.connections.subscribe((connection:MockConnection)=>{
            let options=new ResponseOptions({status: 200, body: {data: fakedHeroes}})
            connection.mockRespond(new Response(options));
        })
        service.getHeroes().then(response=>{
            // console.log(response)
            console.log(response.length)
            expect(response.length).toEqual(2,'should be 4')

        });

        done();
    })
  })

from the console, I can see the length of the response is 4..but the test passes successfully..

Did I miss out anything here?

update1:

I have tried both

expect(response.length).toEqual(2,'should be 4')
expect(response.length).toBe(2,'should be 4')

all pass successfully

like image 456
T_Y Avatar asked Jul 29 '26 13:07

T_Y


1 Answers

The point of done is that is allows you to wait for async tasks to resolve. But you are not waiting for anything. You are calling it synchronously. You should be calling it after the async task resolves (in this case the promise), after you are "done" testing, i.e

service.getHeroes().then(res => {
  expect(...)

  done()
})
like image 195
Paul Samsotha Avatar answered Aug 01 '26 02:08

Paul Samsotha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!