【问题标题】:Unit test dynamic method call Angular单元测试动态方法调用Angular
【发布时间】:2020-09-03 16:16:52
【问题描述】:

我的组件中有这个服务,它的方法之一是动态调用的

@Input methodName: string;

constructor(
        private readonly testService: testService
    ) {
}

loadData() {
   this.testService[this.methodName]().subscribe();
}

我在测试方法 loadData() 时遇到了很多麻烦,它一直告诉我 this.testService[methodName] 不起作用,您将如何测试这种方法?

it('should ',  fakeAsync(() => {
        // getData is the supposed methodName that has to be set;
        testService.getData.and.returnValue(asyncData({} as any));
        component.loadData();
        flush();
        expect(testService.getData).toHaveBeenCalled();
}));

【问题讨论】:

  • 如果答案对你有用,请告诉我
  • @ShashankVivek 成功了,谢谢!你将如何继续模拟组件?
  • 试试medium.com/@shashankvivek.7/…,如果这就是你要找的,请告诉我
  • 也欢迎投票 :)

标签: angular typescript unit-testing jasmine karma-jasmine


【解决方案1】:
  1. 在组件构造函数中创建服务public以便更好地测试

  2. 将此示例作为标准做法:

service.ts

@Injectable({
  providedIn: 'root',
})
export class UserSvcService {
  test() {
    return of('test');
  }
}

对于 component.ts

@Component({
  selector: 'app-user-detail',
  templateUrl: './user-detail.component.html',
  styleUrls: ['./user-detail.component.scss'],
})
export class UserDetailComponent implements OnInit {
  name = 'test';
  val :string

  public constructor(public _userSvc: UserSvcService) {}

  ngOnInit() {
    this._userSvc[this.name]().subscribe(res =>
      this.val = res
    );
  }
}

像这样创建一个存根:


export class UserServiceStub {
  test() {
    return of('test mock');
  }
}

用存根替换实际服务为:

describe('UserDetailComponent', () => {
  let component: UserDetailComponent;
  let fixture: ComponentFixture<UserDetailComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [],
      declarations: [UserDetailComponent],
      providers: [{ provide: UserSvcService, useClass: UserServiceStub }],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(UserDetailComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
    expect(component.val).toBe('test mock'); // move in another "it" block
  });

这应该可行。为了让你的工作方式,你需要创建一个spyOn 服务为public 1st:

it('should ',  () => {       
        spyOn(component.testService,'getData').and.returnValue(return of({some val}));
        component.loadData();
        expect(component.testService.getData).toHaveBeenCalled();
});

这个article可能会让你更感兴趣

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多