我需要监视有角服务中的公共财产。但是此属性没有getter或setter,因此,我无法监视该属性。
始终必须使用该SpyOn
进行获取或设置。如果我不提供,则将其设置为“获取”。 在没有获取者或设定者的情况下,还有其他方法可以模拟或监视公共财产吗?为什么这些方法不可用? 我是否通过公开使用公共财产来使用反模式?
这是我需要模拟的带有公共变量的代码:
@Injectable()
export class StudentService {
public students = [];
.................
}
答案 0 :(得分:0)
您不需要监视单独的属性,因为它们不包含任何业务逻辑。测试的目的之一是确保功能按预期工作。因此,您实际上只需要测试方法,在某些情况下,请检查它们如何影响您的属性,例如expect(component.students).equaltTo(mockStudents2)
。
答案 1 :(得分:0)
我将使用jasmine.createSpyObj
,然后将其附加到该对象。
尝试:
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();
}));
});