简体   繁体   English

Angular Jest 模拟订阅内容

[英]Angular Jest mock subscribe content

How do we mock the content which is consumed by the subscribe method..I am able to initialize the testService but struggling to mock the content of subscribe我们如何模拟订阅方法使用的内容..我能够初始化 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.');
          });
  }
    }

AppComponent应用组件

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

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

    fixture = new AppComponent(
        
    );
});

Try this:尝试这个:

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

You shouldn't mock the subscribe , it will come if you return an observable from the method.你不应该模拟subscribe ,如果你从方法中返回一个observable ,它就会出现。

Edit ======= For the error, you have to do this:编辑 ======= 对于错误,您必须这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM