简体   繁体   English

Angular SpyOn 公共属性

[英]Angular SpyOn public property

I need to spy on the public property in angular service.我需要监视角度服务中的公共财产。 But this property doesn't have getter or setter, therefore, I couldn't spy on that property.但是此属性没有 getter 或 setter,因此,我无法监视该属性。

Always get or set is required to use that SpyOn .始终需要 get 或 set 才能使用该SpyOn If I don't provide it, it is set as 'get'.如果我不提供它,它将被设置为“获取”。 Is there any other way to mock or spy on public property without getter or setter?有没有其他方法可以在没有 getter 或 setter 的情况下模拟或监视公共财产? And why are those methods not available?为什么这些方法不可用? Am I using an anti-pattern by exposing a public property from service?我是否通过暴露服务中的公共属性来使用反模式

This is the code with the public variable that I need to mock:这是我需要模拟的带有公共变量的代码:

@Injectable()
export class StudentService {

  public students = [];
  .................

}

You don't need to spy on separate properties, because they don't contain any business logic.您不需要监视单独的属性,因为它们不包含任何业务逻辑。 One of the purposes of testing is to ensure that functionality works as desired.测试的目的之一是确保功能按预期工作。 So you really need to test only methods, and in some cases check on how they affect your properties, eg expect(component.students).equaltTo(mockStudents2) .所以你真的只需要测试方法,在某些情况下检查它们如何影响你的属性,例如expect(component.students).equaltTo(mockStudents2)

I would use jasmine.createSpyObj and then attach it to this object.我会使用jasmine.createSpyObj然后将它附加到这个对象。

Try:尝试:

describe('Your component test', () => {
  let mockStudentService: any;

  beforeEach(async(() => {
    mockStudentService = jasmine.createSpyObj('studentService', []); 
    // in the empty array put the public methods you require as strings
    mockStudentService.students = []; // mock the public array you want here
    TestBed.configureTestingModule({
      providers: [{ provide: StudentService, useValue: mockStudentService }],
    }).compileComponents();
  }));
});

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

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