代码之家  ›  专栏  ›  技术社区  ›  Adam Tuttle

DOM测试库:当表单头具有相同的文本内容时选择按钮?

  •  0
  • Adam Tuttle  · 技术社区  · 6 年前

    我使用的是DOM测试库,而不是React测试库,但是前者没有标记,所以我使用了后者,因为这似乎是最接近的匹配。希望没问题。

    我有一个身份验证表单,其提交按钮包含文本“登录”,页面还包含具有相同文本内容的标题:

    screen shot of admin login form showing heading "Admin log in" and submit button with text "log in"

    如屏幕截图所示,我实际上已经将标题改为“Admin Log in”,因为这(至少暂时)解决了问题。

    我的测试内容如下:

    import { getByPlaceholderText, getByText } from '@testing-library/testcafe';
    
    const testHostname = process.env.TEST_HOST || 'https://redacted-qa-server';
    
    fixture`Admin Auth`.page`${testHostname}/admin/`;
    
    test('authentication works for a known account', async t => {
        await t
            .typeText(getByPlaceholderText('E-mail address'), username)
            .typeText(getByPlaceholderText('Your password'), password)
            .click(getByText('Log in'));
    
        const location = await t.eval(() => window.location);
        await t.expect(location.pathname).notContains('/login');
    });
    

    值得一提的是,heading和submit按钮目前都在使用CSS将文本样式设置为all caps,但它们都是使用case“login”编码的。

    getByText

    我知道我可以用正则表达式匹配 getByText(/^log in$/i) 不区分大小写,但不允许使用子字符串,但这并不能解决“我不想保留管理员前缀”的问题。

    我知道我可以用 getAllByText

    0 回复  |  直到 6 年前
        1
  •  3
  •   kentcdodds    6 年前

    你可以用 getByText(/log in/i, {selector: 'button'}) 选择登录按钮。

    the upcoming name option 对于 *ByRole getByRole('button', {name: /log in/i}) .

    考虑到两者之间的选择,我想我更喜欢 getByText