【问题标题】:Jest unit test of private variable in AngularAngular中私有变量的开玩笑单元测试
【发布时间】:2020-06-16 06:09:51
【问题描述】:

在我的角度服务中,我使用私有变量并使用 Jest 编写单元测试。 我的服务如下所示:

@Injectable()
export class SampleService {
  private value = '';

  removeValue(): void {
    this.value='';
  }

  setNewValue(value : string): void {
    this.value = value;
  }

  simpleEmptyMethod() {
  }
}

单元测试文件sample.service.spec.ts:

describe('sampleservice', () => {
   let sampleService : SampleService;
   beforeEach(() => {
      TestBed.configureTestingModule({
        providers : [SampleService]
      });
      sampleService=TestBed.get(SampleService);
   });

   it('should be created', () => {
     expect(sampleService).toBeTruthy();
   })

   it('should remove Value', () => {
     sampleService.removeValue();
     expect(sampleService.value).toBe('');
   })

   it('should set new value', () => {
       sampleService.setNewValue('abc');
       expect(sampleService.value).expect('abc');
   })

})

我,收到类似“值未定义”的错误。这可能是因为该值在服务类中是私有的,以及在将来定义方法主体时覆盖空方法的方法是什么。 这种情况如何处理?

【问题讨论】:

  • 它是私有的,你不能访问它。将其公开,或者在您的测试类中模拟该值,或者编写一个方法 getValue() 来获取该值并调用该方法。

标签: angular jestjs


【解决方案1】:

我无法重现您的错误。即使该变量是私有的并且您不应该访问它,它仍然是可能的。 Here's a stackblitz demonstrating the tests passing. 你会注意到测试仍然运行并通过,但 IDE 告诉我:

“属性‘值’是私有的,只能在类内访问 'SampleService'"

我会推荐:

  1. 确保您是针对接口而不是实现进行测试。
  2. 如果您需要检查此服务的状态,请将value 属性设为公开,或添加公开的getValue() 函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-02
    • 2017-10-01
    • 2018-09-10
    • 2021-01-24
    • 2019-01-08
    • 2018-07-14
    • 2021-02-05
    • 1970-01-01
    相关资源
    最近更新 更多