codegen.test.ts 673 B

1234567891011121314151617181920212223242526
  1. import { expect, test } from './index'
  2. import { z } from 'zod'
  3. test('scrapes top 3 stories from Hacker News', async ({ page, scraper }) => {
  4. await page.goto('https://news.ycombinator.com')
  5. const schema = z.object({
  6. top: z
  7. .array(
  8. z.object({
  9. title: z.string(),
  10. })
  11. )
  12. .length(3)
  13. .describe('Top 3 stories on Hacker News'),
  14. })
  15. // Generate scraping code
  16. const { code } = await scraper.generate(page, schema)
  17. // Evaluate the generated code in the page context
  18. const result: z.infer<typeof schema> = await page.evaluate(code)
  19. // Validate the result
  20. expect(schema.safeParse(result).success).toBe(true)
  21. })