【问题标题】:Sinon create stub instance - include protected propertiesSinon 创建存根实例 - 包括受保护的属性
【发布时间】:2019-02-20 10:00:55
【问题描述】:

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

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

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(manager);”线。 上面的代码产生以下异常:

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

有没有办法告诉诗浓包含这些属性? 任何帮助将不胜感激。

【问题讨论】:

  • 我也有类似的问题。只是用上面的例子稍微解释一下这个问题。 repo.doSomething(){entityManager.doIt()};我只想验证 repo.doSomething 何时被调用,entityManager.doIt() 被调用一次

标签: sinon


【解决方案1】:

我用

解决了这个问题
repo = new Repo(manager as any);

【讨论】:

    【解决方案2】:

    我不知道在你的情况下 RepoEntityManager 做了什么,我也不完全清楚你想在这里测试什么......所以基于此,我的回答有点笼统,但也许它为您指明了正确的方向。

    我的想法:也许你应该将它们解耦。我会通过以下方式处理它:

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

      ma​​nager.getRepos.returns(mockedRepos);

    这样您的测试中就不需要受保护的存储库变量。

    【讨论】:

    • 但仍然请考虑您想要实现的目标.. EntityManager 有 Repos,Repo 有 EntityManager,这在我看来是一个奇怪的概念,并且有点像循环依赖.. 东西这样总是很难测试。
    • 我没有看到 EntityManager 有 Repo。我有一个类似的问题,我想测试的类有依赖注入。但是,传入的参数(在上述情况下为 EntityManager)具有不允许我使用 sinonStubbedInstance 的私有字段。这个私有字段并不重要,可以是任何东西
    猜你喜欢
    • 2011-09-12
    • 2011-03-11
    • 2020-03-31
    • 2011-06-06
    • 2018-05-05
    • 2021-06-07
    • 2016-02-19
    • 2012-10-13
    • 2014-04-15
    相关资源
    最近更新 更多