Published on

Fix for "TypeError: text is not iterable" error in Puppeteer

Authors

Recently, I was automating a financial workflow that requires OTP, and I wrote logic for that. Everything works as expected in terms of forwarding that OTP to an endpoint and things like that.

However, when I was typing that OTP like this:

const otp = 123456;
await page.type("#userid-otp", otp)

I was greeted with error message

TypeError: text is not iterable
    at Keyboard.type (file:///Users/example/node_modules/puppeteer-core/lib/esm/puppeteer/common/Input.js:202:28)
    at CDPElementHandle.type (file:///Users/example/node_modules/puppeteer-core/lib/esm/puppeteer/common/ElementHandle.js:369:115)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async IsolatedWorld.type (file:///Users/example/node_modules/puppeteer-core/lib/esm/puppeteer/common/IsolatedWorld.js:213:9)
    at async exampleWorkflow (webpack-internal:///(api)/./src/defer/example/website.js:133:9)
    at async execLocally (file:///Users/example/node_modules/@defer/client/esm/index.js:32:26)

Initially, I thought that was on one of the cases and ran the script multiple times and still got the same error.

Thought, I was entering the OTP before the element was visible in DOM so watched for the selector like this.

await page.waitForSelector("#userid-otp")
const otp = 123456;
await page.type("#userid-otp", otp)

And that didn't help as well.

So what's the reason for this issue?

It's because I was trying to assign a number to a text.

Fix

Just convert the number to a string using string literals or by using .toString() method.

const otp = 123456;
await page.type("#userid-otp", otp?.toString())

And that's pretty much it.

Happy fixing bugs!