Angular jasmine: 属性 没有访问类型 get

Angular jasmine: Property does not have access type get

我知道已经有人问过类似的问题,但到目前为止还没有解决我的问题。也许我遗漏了什么。

我有这个服务有一个 getter 我想模拟

export class UserService {
    private activeUserSubject: BehaviorSubject<UserModel>;
  
    constructor() {
      this.activeUserSubject = new BehaviorSubject<UserModel>(UserHelper.getCurrentUser());
    }
  
    public get activeUserValue(): UserModel {
      return this.activeUserSubject.value;
    }
}

所有其他答案都建议使用 SpyOn属性,但它对我不起作用。在我的规范中,我尝试创建和模拟它,但我收到错误 属性 activeUserValue does not have access type get.

describe('MyComponent', () => {
    ///other
    let authenticationService: jasmine.SpyObj<UserService>;

    beforeEach(async () => {
    userService = jasmine.createSpyObj<UserService>(['activeUserValue']);

    await TestBed.configureTestingModule({
        imports: [
            ///
        ],
        declarations: [
            ///
        ],
        providers: [
        { provide: UserService, useValue: userService }
        ]
    })
        .compileComponents();
    });

    fit('should create', () => {
        const spy = spyOnProperty(userService, 'activeUserValue', 'get').and.returnValue(of(getMockUser()));
        fixture.detectChanges();
        expect(spy).toBe(getMockUser());
    });
}

我做错了什么?

请记住,当您执行 spyOnProperty(userService, 时,您是在说此 getter 存在于您创建的 spyObject 上,而实际上它不存在。一旦你模拟了 UserService,它的实现(它是否使用 getter 或不使用什么)就在 window 之外,我们应该使用模拟。

我会做以下事情(在评论后面加上!!):

describe('MyComponent', () => {
    ///other
    let authenticationService: jasmine.SpyObj<UserService>;

    beforeEach(async () => {
    userService = jasmine.createSpyObj<UserService>(['activeUserValue']);
    // !! attach activeUserValue to the spyObject
    userService.activeUserValue = of(getMockUser());
    await TestBed.configureTestingModule({
        imports: [
            ///
        ],
        declarations: [
            ///
        ],
        providers: [
        { provide: UserService, useValue: userService }
        ]
    })
        .compileComponents();
    });

    fit('should create', () => {
        // !! remove this line
        fixture.detectChanges();
        expect(spy).toBe(getMockUser());
    });
}