如何测试使用大型配置对象的服务



如果I组件有一个大型配置对象,打算由几个内部服务使用,但单个服务可能只对该配置中的一个或两个属性感兴趣。。。我该如何处理测试?

在我的测试中,我试图只传递一个Partial<MyLargeConfig>,其中只设置了相关的属性,但我收到了关于一个属性对于分部是可选的,但在实际接口中是必需的错误。

我如何才能绕过这一点,而不必让我的测试在设置了所有属性的情况下声明一些令人讨厌的配置对象?有没有办法告诉typescript只允许在我的测试上下文中使用分部?

我想避免在所有属性的末尾添加?。。。这似乎是错误的解决方案。在测试中声明所有属性似乎也是错误的解决方案。

***编辑***

为了使其不那么抽象(但仍然有点抽象(,我正在做的是构建一个配置对象,并将其传递给一个组件,例如:

interface MyLargeConfig {
a: string,
b: number,
c: boolean,
d: () => void,
e: ...etc
}
<my-component [config]="config"></my-component>

然后组件内部会进行

this.serviceA = new InteralService(this.config); // only makes use of  properties a & c in the config
this.serviceB = new OtherInteralService(this.config); // only makes use of  properties b & d in the config
this.serviceC = new YetAnotherInteralService(this.config); // // only makes use of  properties c & f in the config

您的测试需要符合生产代码中的类型。否则,你可能会错过各种各样的错误。在这种情况下,您确实需要所有的配置属性,因为无论您是否关心测试,这些内部服务都会被实例化。

为了减少麻烦,我可能会设置一些函数来生成夹具数据。

function configPropsFixture(values?: Partial<MyLargeConfig>): MyLargeConfig {
return {
a: 'foo',
b: 123,
c: true,
d: () => undefined,
...values
}
}

该函数设置了一些典型的默认值,并允许您传入一个覆盖任何这些默认值的对象。

例如:

function myComponent(config: MyLargeConfig) {
//...
}
// some tests test
const result = myComponent(configPropsFixture())
const resultA = myComponent(configPropsFixture({ a: 'bar' }))
const resultB = myComponent(configPropsFixture({ b: 456 }))

这符合组件的类型约定,同时也使在特定道具上测试特定值变得非常简单。

游乐场


此外,我不知道InteralService及其同类是如何定义它们的参数的,但这些参数应该作为大型配置的子集键入:

class InteralService {
constructor(args: Pick<MyLargeConfig, 'a' | 'b'>) {}
}
class OtherInteralService {
constructor(args: Pick<MyLargeConfig, 'c' | 'd'>) {}
}

或者:

interface InteralServiceProps {
a: string,
b: number,
}
class InteralService {
constructor(args: InteralServiceProps) {}
}
interface OtherInteralServiceProps {
c: boolean,
d: () => void,
}
class OtherInteralService {
constructor(args: OtherInteralServiceProps) {}
}
interface MyLargeConfig extends InteralServiceProps, OtherInteralServiceProps {
e: string // other props here?
}

您总是可以传入比类型期望的更多的属性,因此这应该可以正常工作。然后,当单元测试这些内部服务时,您只需要传递这些服务所需的道具。

游乐场

最新更新