How to call describe or it function in afterEach function in jasmine

Viewed 158

I'd like to check button disable state after each it funtion. So I use afterEach function but error like below was occured.
How to call describe or it function in afterEach function or any workarround.

'it' should only be used in 'describe' function
  describe('Input Error Check', () => {
    const fixture = TestBed.createComponent(AppComponent);

    afterEach( () => {
      const searchButon = fixture.debugElement.query(By.css('#searchButton')).nativeElement as HTMLButtonElement
      expect(searchButon.disabled).toBeTruthy()
    })

    it('No Input Value', () =>{
      // write test code
    })


    it('Invalid Input Value', () =>{
      // write test code
    })
    
  })
1 Answers

The afterEach method is done for teardown logic only. The jasmine docs about it say:

Run some shared teardown after each of the specs in the describe in which it is called.

You might add this expect in the end of each test of make a small proxy like in the code below:

function withSearchButtonDisabled(testCallback) {
   return () => {
      testCallback();
      const searchButon = fixture.debugElement.query(By.css('#searchButton')).nativeElement as HTMLButtonElement
      expect(searchButon.disabled).toBeTruthy()
   }
}

  describe('Input Error Check', () => {
    const fixture = TestBed.createComponent(AppComponent);

    it('No Input Value', withSearchButtonDisabled(() =>{
      // write test code
    }))


    it('Invalid Input Value', withSearchButtonDisabled(() =>{
      // write test code
    }))
    
  })

PS I didn't test the code, there might be typos

Related