angularjestjsrxjs

Unit test seems not to trigger RxJS stream


Here is my test:

  it( 'should drop element', ( done ) => {

    component.media.init$.pipe(
      filter( isInit => !!isInit ),
      take( 1 ),
      tap( _ => {

        console.log('hello')

        fixture.detectChanges();

        const dNDDirective = fixture.debugElement.query( By.directive( DnDClipDirective ) );

        ( dNDDirective.componentInstance as DnDClipDirective ).drop$.emit( {
          event:<Event>{
            target:{}
          },
          files:[{
            audio:new ArrayBuffer(0),
            url:'test',
            filename:'test'
          }]
        });

        component.filesService.isDragFromTree = true;

        component.filesService.draggedFile = { audio:new ArrayBuffer( 0 ), url:'test', filename:'test' };

        const spyObj = jest.spyOn( component.media, 'dropAudioElements' );

        expect( spyObj ).toHaveBeenCalledTimes( 1 )

        expect( component.filesService.files ).toHaveLength( 1 );

        done()

        console.log( "HELLO 2")

      } )
    ).subscribe()

    console.log('HELLO')

    component.media.init$.next( true );

  }, 6000 )

The done is never triggered and I get a timeout error.


Solution

  • It's unclear without looking at the source, but you can remove take maybe that is why the subscribe isn't working ( if init$ is a behaviour subject then take might ignore the second emit! ), also can you remove the ,6000 at the end, I am unsure what that one does!

     it( 'should drop element', ( done ) => {    
        component.media.init$.pipe(
          filter( isInit => !!isInit ),
          tap( _ => {
            console.log('hello')
            fixture.detectChanges();
            const dNDDirective = fixture.debugElement.query( By.directive( DnDClipDirective ) );
            ( dNDDirective.componentInstance as DnDClipDirective ).drop$.emit( {
              event:<Event>{
                target:{}
              },
              files:[{
                audio:new ArrayBuffer(0),
                url:'test',
                filename:'test'
              }]
            });
            component.filesService.isDragFromTree = true;
            component.filesService.draggedFile = { audio:new ArrayBuffer( 0 ), url:'test', filename:'test' };
            const spyObj = jest.spyOn( component.media, 'dropAudioElements' );
            expect( spyObj ).toHaveBeenCalledTimes( 1 );
            expect( component.filesService.files ).toHaveLength( 1 );
            done();
            console.log( "HELLO 2");
          })
        ).subscribe()
        console.log('HELLO')
        component.media.init$.next( true );
      })