【问题标题】:Angular Jest mock subscribe contentAngular Jest 模拟订阅内容
【发布时间】:2021-05-06 19:24:54
【问题描述】:

我们如何模拟订阅方法消耗的内容..我能够初始化 testService 但努力模拟订阅的内容

export class AppComponent {


constructor(){}



     CheckTestLink(link: any) {
     this.testService.init().subscribe( configUsers => {
            const conf: [] = configUsers['entries'].filter( entry =>
              (this.userName === entry.content.properties.user_name );
            if (conf.length > 0) {
 
             
            } else {
 
             
            }
          },
          errors => {
  
            this.ErrorService.notifyError('Error fetching details.');
          });
  }
    }

应用组件

    describe( 'AppComponent', () => {
    let fixture: AppComponent;
     let TestServiceMOck;

beforeEach( () => {
    TestServiceMOck={
     init:jest.fn().mockImplementation(subscribe=>{return of('test')})
      }

    fixture = new AppComponent(
        
    );
});

【问题讨论】:

    标签: angular unit-testing testing jestjs


    【解决方案1】:

    试试这个:

    TestServiceMOck={
         init:jest.fn().mockReturnValue(of({ entries: [{ 
               content: { properties : { user_name: 'hola' } } }] }))
          }
    

    你不应该模拟subscribe,如果你从方法中返回一个observable,它就会出现。

    编辑 ======= 对于错误,您必须这样做:

    import { throwError } from 'rxjs';
    ....
    TestServiceMOck={
         init:jest.fn().mockReturnValue(throwError({}))
          }
    

    【讨论】:

    • 知道了..但是我如何模拟这部分 .subscribe( configUsers => { const conf: [] = configUsers['entries'].filter( entry => (this.userName == = entry.content.properties.user_name ); if (conf.length > 0) { } else { } }, errors => { this.ErrorService.notifyError('Error fetching details.'); });
    • 你必须模拟 of 里面的内容。查看我的编辑。
    • 谢谢它的工作..只有错误部分不起作用。我正在尝试这个 const 错误: HttpErrorResponse = { status: 401, message: 'You are not logged in' } as HttpErrorResponse;TestServiceMOck={ init:jest.fn().mockReturnValue( throwError(error)) }
    猜你喜欢
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 2021-08-09
    • 1970-01-01
    • 2010-09-24
    相关资源
    最近更新 更多