【问题标题】:How to test if component hast only the allowed props and uses only the allowed classes with Jest?如何测试组件是否仅具有允许的道具并且仅使用 Jest 允许的类?
【发布时间】:2021-02-22 07:31:57
【问题描述】:

我有一个如下所示的 Button 组件:

const Button = ({
    children,
    type,
    btnStyles,
    onClick,
}: any) => {
    //...
}

export default Button

我不想确保该按钮仅与上面定义的允许道具一起使用。我的测试目前看起来像这样:

it('should only have the allowed props', () => {
    const tree = shallow(
        <Button
            type='button'
            buttonStyles='a-custom-button'
            onClick={() => {
                console.log('Custom Button Clicked')
            }}
        >
            <i></i>
            Button
        </Button>
    )

    expect(tree.prop('type')).toBeDefined()
    expect(tree.prop('buttonStyles')).toBeDefined()
})

我还想确保按钮样式只能使用允许的类名。例如按钮只能包含.a-custom-button.a-custom-button-styles 类。

我怎样才能用 Jest 做到这一点?

【问题讨论】:

  • 如果您提供正确的道具类型而不是任何类型,则无需对其进行测试。

标签: reactjs unit-testing jestjs jasmine react-testing-library


【解决方案1】:

@Clarity 是正确的。您正在使用 TypeScript,因此您可以使用有效类名的联合:

type ButtonProps = {
  btnStyles: 'a-custom-button' | 'a-custom-button-styles';
}

const Button = ({
    btnStyles,
}: ButtonProps) => {
   console.log(btnStyles);
   return null;
}

Button({ btnStyles: 'a-custom-button' })        // works
Button({ btnStyles: 'a-custom-button-styles' }) // also works
Button({ btnStyles: 'invalid-class-name' })     // doesn't work - invalid prop value in TypeScript

游乐场: https://www.typescriptlang.org/play?#code/C4TwDgpgBAQgrsYB7AdgBQE5LAZygXigG8AoKKAI2BQGVQAbCHALigHIBDAWgGM4dkAWy4UEyFGygAfdtz4Ckw0YlRcBIRjjYBuEgF8SJHqgGwxqAlAAUpcuSq0GTADT7W8Feiy4AlAQB8xGTkxig4SIwAdPRIAOZWDnQaTD66dhgQwHAYKFAocPT0ugYkHuI2lNRJmqycvPxCIuYSUHp+dh0A9J1QAO5IGADWOKXNFYlOLLL1CkrNapOSbVDdUBz04X0Dw6Oe41WTtQCWKABu60cAJrz0HDg4XCgcghBL7XarJ+f0V1Bg3lBvnBoAAVcAQGg8DBHMDAKAQDBYDAkIA

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-13
    • 1970-01-01
    • 2023-01-10
    • 2021-06-02
    • 2011-02-16
    • 1970-01-01
    • 2012-10-12
    • 2021-12-13
    相关资源
    最近更新 更多