mercredi 9 octobre 2019

typescript jest override mock return value

I want to override a mockReturnValue or mockImplementation of a function with Jest, so in the main beforeEach I set the value as an empty array and in the test where I want some data I try to override it (tried by macking a mockService and then spying on that, jest.unmock, mockReset, etc) but it keeps on returning the value of the first mock is there a simple way to override a mock?

describe('component', () => {
   let service: Service;
   let getValueSpy;
   beforeEach(async(() => {
      TestBed.configureTestingModule with providers and imports
      service = TestBed.get(Service);
      getValueSpy = jest.spyOn(service, 'getValue').mockReturnValue(of([]));
   }));
   describe('component', () => {
      beforeEach(() => {
         getValueSpy.mockReturnValue(of[{code:'long implementation'}]);
      });
      it('should get long implementation', done => {
         component.value$.subscribe( result => {
           expect(result).toStrictEqual([{code: 'long implementation'}]); //fails result is []
         });
      }, 1000);
   }
}

Hope this simplified version is still readable.

Aucun commentaire:

Enregistrer un commentaire