codegen.test.ts 769 B

12345678910111213141516171819202122232425262728293031
  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. throw new Error(code)
  18. // Evaluate the generated code in the page context
  19. const result = await page.evaluate(code)
  20. // Validate the result
  21. const parsed = schema.safeParse(result)
  22. expect(parsed.success).toBe(true)
  23. if (parsed.success) {
  24. expect(parsed.data.top).toHaveLength(3)
  25. }
  26. })