使用 React 的 Jest-Puppeteer 测试不会在输入中键入文本



我有一个从"create-react-app"创建的应用程序,我添加了用于运行端到端测试的puppeteer。在尝试运行登录测试时,我无法在登录表单输入中键入文本。

jest-puppeteer.config.js:

module.exports = {
server: {
command: `npm start`,
port: 3000,
launchTimeout: 10000,
debug: true
}
};

jest.config.js:

module.exports = {
preset: 'jest-puppeteer',
testRegex: './*\index.test\.js$'
};

我的登录测试:

it('should login test user', async () => {
await page.waitForSelector('form[name="login"]');
await expect(page).toFillForm('form[name="login"]', {
username: 'abcd',
password: 'abcd'
});
await expect(page).toMatchElement('input[name="username"]', { text: 'abcd' });
}

我还尝试过使用以下任何一种:

await page.type('#username', 'abcd');

await page.click('input[name="username"]');
await page.type('input[name="username"]', 'abcd');

await expect(page).toFill('input[name="username"]', 'abcd');

但是,它仍然没有键入任何文本。我想知道我的设置是否适合创建react应用程序。知道怎么解决这个问题吗?

Puppeter默认情况下是无头运行的,我相信它确实在后台运行。

在您的jest-puppeteer.config.js中添加以下行:

launch: {
headless: false,
}

所以它看起来是这样的:

module.exports = {
launch: {
headless: false,
},
server: {
command: `npm start`,
port: 3000,
launchTimeout: 10000,
debug: true
}
};

这将真正打开浏览器,你将能够看到发生了什么。

在继续之前,请检查您的应用程序,并检查选择器是否错误。不知怎的,在使用Jest之类的测试框架或任何你喜欢的东西之前,我更喜欢只单独使用puppeteer,看看代码是否运行良好、流畅。

不要忘记在开始测试时添加headless : false

你可以试试这个。

describe('Login', () => {
beforeAll(async () => {
await page.goto('https://localhost:3000');
})
it('should login test user', async () => {
const waitForTheName = await page.waitForSelector('input[name="username"]');
const focusInputName = await page.focus('input[name="username"]')
const writeInputName = await page.keyboard.type('abcd')
const focusInputPaswd = await page.focus('input[name="password"]')
const writeInputPaswd = await page.keyboard.type('abcd')
await expect(page).toFillForm('form[name="login"]', {
username: 'abcd',
password: 'abcd'
})
await expect(page).toMatchElement('input[name="username"]', { text: 'abcd' })
}
})

最新更新