Sinon创建存根实例 - 包括受保护的属性

问题描述 投票:1回答:1

我的问题是在创建存根实例时如何包含受保护的属性。

在我的开玩笑测试中,我有:

const sandbox = createSandbox();
let manager: SinonStubbedInstance<EntityManager>;
let repo: Repo;

beforeEach(() => {
    manager = sandbox.createStubInstance(EntityManager);
    repo = new Repo(manager);
});

afterEach(() => sandbox.restore());

这是试图制作一个存根:

export declare class EntityManager {

/**
 * Connection used by this entity manager.
 */
readonly connection: Connection;

/**
 * Custom query runner to be used for operations in this entity manager.
 * Used only in non-global entity manager.
 */
readonly queryRunner?: QueryRunner;

/**
 * Once created and then reused by en repositories.
 */
protected repositories: Repository<any>[];

/**
 * Plain to object transformer used in create and merge operations.
 */
.......
}

因此,我似乎无法在存根中包含只读属性和受保护的属性。

在“repo = new Repo(经理);”线。上面的代码产生以下异常:

Argument of type 'SinonStubbedInstance<EntityManager>' is not assignable to parameter of type 'EntityManager'.
Property 'repositories' is missing in type 'SinonStubbedInstance<EntityManager>'.ts(2345)

无论如何要告诉Sinon包括房产?非常感激任何的帮助。

sinon
1个回答
0
投票

我不知道你的情况下Repo对EntityManager有什么影响,我也不完全清楚你想在这里测试什么..所以基于这个我的答案有点通用,但也许它指向你正确的方向。

我的想法:也许你应该将它们分开。我会通过以下方式接近它:

  1. 在EntityManager中创建一个获取所有repos的getter,将其命名为getRepos()
  2. 创建一个包含一些Repos ... const mockedRepos的模拟数组;
  3. 使用存根实例模拟EntityManager的getter,返回模拟数据: manager.getRepos.returns(mockedRepos);

这样,您的测试中不需要受保护的存储库var。


0
投票

我解决了这个问题

repo = new Repo(manager as any);
© www.soinside.com 2019 - 2024. All rights reserved.