在类实例[TypeScript]上测试私有属性

在类实例[TypeScript]上测试私有属性,typescript,jestjs,Typescript,Jestjs,我有一个带构造函数的类 export default class S3Client { private readonly s3: S3; private readonly bucketName: string; private readonly useS3Data: boolean; constructor(configuration: IConfig = config, region: string = 'eu-west-1') { this.bucketName =

我有一个带构造函数的类

export default class S3Client {
  private readonly s3: S3;
  private readonly bucketName: string;
  private readonly useS3Data: boolean;

  constructor(configuration: IConfig = config, region: string = 'eu-west-1') {
    this.bucketName = configuration.bucketName;
    this.s3 = new S3({ region });
    this.useS3Data = [ 'int', 'test', 'live' ].includes(configuration.env);
  }
...
}
这是手动编写的,不是由IDE编写的,因此需要测试(此外,没有这些测试,代码覆盖率检查器也不满意)

是的,它们是通过此类上的测试方法间接测试的,但是如何直接测试属性

describe('constructor', () => {
  // mock setup stuff here
  test('as expected', () => {
    const clientUnderTest = new S3Client(mockEnvValueObjPassedIn);
    expect(clientUnderTest.bucketName).toEqual('test-bucket-name');
  });
});
`` 这显然不起作用,因为
bucketName
是私有的。 我尝试了另一个带有
Object.getPrototypeOf(clientUnderTest)的
clientUnderTest
原型但是由于原型工作的复杂方式,它只生成一个空对象,但似乎知道
object.getOwnPropertyNames(clientUnderTest)
的属性。 我尝试复制该对象,因为我可以用
object.assign({},underTest)控制台记录我的
clientUnderTest
的字符串化版本 我对这本书不感兴趣

  • 制造吸气剂
  • 公开这些价值观
  • 使它们受到保护,然后生成可访问的子类
  • 任何其他黑客,我必须妥协我的代码只是为了满足一个测试

对于
const a=新的S3Client
a['bucketName']
起作用,这就是我最后使用的。

可能重复的