【问题标题】:Type checks with runtypes使用运行类型进行类型检查
【发布时间】:2020-09-28 10:00:57
【问题描述】:

我正在尝试使用pelotom/runtypes 库验证具有Mocha 的对象的配置部分;但我收到错误“预期为真”:

//>>>>> declaration:
export const PluginConfigurationNotRequiredType = Record({
    plugin_configuration: Record({
        type: Literal("plugin_configuration_not_required")
    })
});

export type PluginConfigurationNotRequiredType = Static<
    typeof PluginConfigurationNotRequiredType
>;


//>>>>> the object to test: I want to test only the "plugin_configuration" part; it must be with type: "plugin_configuration_not_required":
{test:{
plugin_configuration: {
            type: "plugin_configuration_not_required"
        },
value: 1}
}

//>>>>> the test:
it("should use a valid plugin not required configuration", () => {
    const config = getConfiguration();
    expect(
        PluginConfigurationNotRequiredType.validate(config.plugin_configuration)
            .success
    ).to.be.true;
});

【问题讨论】:

    标签: javascript typescript testing types runtypes


    【解决方案1】:

    我认为发生这种情况的原因是您正在针对其包装器测试类型/对象的“内部”属性。

    我尚未对此进行测试,但这样做应该可以:

    PluginConfigurationNotRequiredType.validate(config);
    

    或者,如果您想测试内部属性,则可以在该示例的顶部声明 2 个运行类型,如下所示:

    const PluginConfigurationInner = Record({
        type: Literal("plugin_configuration_not_required")
    });
    export const PluginConfigurationNotRequiredType = Record({
        plugin_configuration: PluginConfigurationInner
    });
    

    那么您的测试代码将使用第一个“记录”声明进行测试:

    PluginConfigurationInner.validate(config.plugin_configuration);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      • 2018-10-30
      • 1970-01-01
      • 2013-11-02
      • 2020-03-20
      • 2019-01-09
      • 2019-11-20
      相关资源
      最近更新 更多