ronantakizawa/codereview-bench huggingface dataset:
Repository: cypress-io/cypress
File: packages/driver/cypress/integration/commands/navigation_spec.js (JavaScript)

Code before:
const Cookie = require('js-cookie')
const { stripIndent } = require('common-tags')
const helpers = require('../../support/helpers')

const { _, Promise, $ } = Cypress

describe('src/cy/commands/navigation', { retries: 2 }, () => {
  context('#reload', () => {
    before(() => {
      cy
      .visit('/fixtures/generic.html')
      .then(function (win) {
        this.body = win.document.body.outerHTML
      })
    })

    beforeEach(function () {
      const doc = cy.state('document')

      this.win = cy.state('window')

      $(doc.body).empty().html(this.body)
    })

    afterEach(function () {
      cy.state('window', this.win)
    })

    it('calls into window.location.reload', () => {
      const locReload = cy.spy(Cypress.utils, 'locReload')

      cy.reload().then(() => {

Review comment (suggestion):
```suggestion
describe('src/cy/commands/navigation', () => {
```

Code after:
const Cookie = require('js-cookie')
const { stripIndent } = require('common-tags')
const helpers = require('../../support/helpers')

const { _, Promise, $ } = Cypress

describe('src/cy/commands/navigation', () => {
  context('#reload', () => {
    before(() => {
      cy
      .visit('/fixtures/generic.html')
      .then(function (win) {
        this.body = win.document.body.outerHTML
      })
    })

    beforeEach(function () {
      const doc = cy.state('document')

      this.win = cy.state('window')

      $(doc.body).empty().html(this.body)
    })

    afterEach(function () {
      cy.state('window', this.win)
    })

    it('calls into window.location.reload', () => {
      const locReload = cy.spy(Cypress.utils, 'locReload')

      cy.reload().then(() => {
Repository: cypress-io/cypress
File: packages/driver/cypress/integration/commands/request_spec.js (JavaScript)

Code before:
const { stripIndent } = require('common-tags')
const { _, Promise } = Cypress

const RESPONSE_TIMEOUT = 22222

describe('src/cy/commands/request', { retries: 2 }, () => {
  context('#request', {
    responseTimeout: RESPONSE_TIMEOUT,
  }, () => {
    beforeEach(() => {
      cy.stub(Cypress, 'backend').callThrough()
    })

    describe('argument signature', () => {
      beforeEach(function () {
        const backend = Cypress.backend
        .withArgs('http:request')
        .resolves({ isOkStatusCode: true, status: 200 })

        this.expectOptionsToBe = function (opts) {
          _.defaults(opts, {
            failOnStatusCode: true,
            retryOnNetworkFailure: true,
            retryOnStatusCodeFailure: false,
            encoding: 'utf8',
            gzip: true,
            followRedirect: true,
            timeout: RESPONSE_TIMEOUT,
            method: 'GET',
          })


Review comment (suggestion):
```suggestion
describe('src/cy/commands/request', () => {
```

Code after:
const { stripIndent } = require('common-tags')
const { _, Promise } = Cypress

const RESPONSE_TIMEOUT = 22222

describe('src/cy/commands/request', () => {
  context('#request', {
    responseTimeout: RESPONSE_TIMEOUT,
  }, () => {
    beforeEach(() => {
      cy.stub(Cypress, 'backend').callThrough()
    })

    describe('argument signature', () => {
      beforeEach(function () {
        const backend = Cypress.backend
        .withArgs('http:request')
        .resolves({ isOkStatusCode: true, status: 200 })

        this.expectOptionsToBe = function (opts) {
          _.defaults(opts, {
            failOnStatusCode: true,
            retryOnNetworkFailure: true,
            retryOnStatusCodeFailure: false,
            encoding: 'utf8',
            gzip: true,
            followRedirect: true,
            timeout: RESPONSE_TIMEOUT,
            method: 'GET',
          })
Repository: cypress-io/cypress
File: packages/data-context/test/unit/data-context.spec.ts (TypeScript)

Code before:
import { expect } from 'chai'
import { DataContext } from '@packages/data-context'
import snapshot from 'snap-shot-it'

const makeDataContext = (options) => {
  return new DataContext({
    launchOptions: {},
    launchArgs: {},
    appApi: {
      getBrowsers: () => ({}),
    },
    authApi: {},
    projectApi: {
      getProjectRootsFromCache: () => ([]),
    },
    ...options,
  })
}

describe('@packages/data-context', () => {
  describe('initializeData', () => {
    it('should initialize', async () => {
      const context = makeDataContext()

      await context.initializeData()
      snapshot(context)
    })

    it('should skip first wizard step when given a testingType', async () => {
      const context = makeDataContext({
        launchArgs: {
          testingType: 'e2e',
        },
      })

      await context.initializeData()
      expect(context._coreData.wizard).to.contain({
        chosenTestingType: 'e2e',
        currentStep: 'initializePlugins',
      })
    })
  })
})


Review comment (suggestion):
```suggestion
    it('initializes', async () => {
```

This is a real nitpick, but adding "should" to the beginning of every test title ends up being superfluous.

Code after:
import { expect } from 'chai'
import { DataContext } from '@packages/data-context'
import snapshot from 'snap-shot-it'

const makeDataContext = (options) => {
  return new DataContext({
    launchOptions: {},
    launchArgs: {},
    appApi: {
      getBrowsers: () => ({}),
    },
    authApi: {},
    projectApi: {
      getProjectRootsFromCache: () => ([]),
    },
    ...options,
  })
}

describe('@packages/data-context', () => {
  describe('initializeData', () => {
    it('initializes', async () => {
      const context = makeDataContext()

      await context.initializeData()
      snapshot(context)
    })

    it('skips first wizard step when given a testingType', async () => {
      const context = makeDataContext({
        launchArgs: {
          testingType: 'e2e',
        },
      })

      await context.initializeData()
      expect(context._coreData.wizard).to.contain({
        chosenTestingType: 'e2e',
        currentStep: 'initializePlugins',
      })
    })
  })
})
Repository: cypress-io/cypress
File: packages/data-context/test/unit/data-context.spec.ts (TypeScript)

Code before:

const makeDataContext = (options) => {
  return new DataContext({
    launchOptions: {},
    launchArgs: {},
    appApi: {
      getBrowsers: () => ({}),
    },
    authApi: {},
    projectApi: {
      getProjectRootsFromCache: () => ([]),
    },
    ...options,
  })
}

describe('@packages/data-context', () => {
  describe('initializeData', () => {
    it('should initialize', async () => {
      const context = makeDataContext()

      await context.initializeData()
      snapshot(context)
    })

    it('should skip first wizard step when given a testingType', async () => {
      const context = makeDataContext({
        launchArgs: {
          testingType: 'e2e',
        },
      })

      await context.initializeData()
      expect(context._coreData.wizard).to.contain({
        chosenTestingType: 'e2e',
        currentStep: 'initializePlugins',
      })
    })
  })
})


Review comment (suggestion):
```suggestion
    it('skips first wizard step when given a testingType', async () => {
```

Code after:

const makeDataContext = (options) => {
  return new DataContext({
    launchOptions: {},
    launchArgs: {},
    appApi: {
      getBrowsers: () => ({}),
    },
    authApi: {},
    projectApi: {
      getProjectRootsFromCache: () => ([]),
    },
    ...options,
  })
}

describe('@packages/data-context', () => {
  describe('initializeData', () => {
    it('initializes', async () => {
      const context = makeDataContext()

      await context.initializeData()
      snapshot(context)
    })

    it('skips first wizard step when given a testingType', async () => {
      const context = makeDataContext({
        launchArgs: {
          testingType: 'e2e',
        },
      })

      await context.initializeData()
      expect(context._coreData.wizard).to.contain({
        chosenTestingType: 'e2e',
        currentStep: 'initializePlugins',
      })
    })
  })
})
Repository: cypress-io/cypress
File: packages/frontend-shared/cypress/support/mock-graphql/stubgql-Project.ts (TypeScript)

Code before:
import _ from 'lodash'
import { randomComponents } from '../../../src/graphql/specs/testStubSpecs'
import config from '@packages/desktop-gui/cypress/fixtures/config.json'

import type {
  Project,
  CodegenTypeMap,
} from '../generated/test-graphql-types.gen'
import { MaybeResolver, testNodeId } from './clientTestUtils'

export const createTestProject = (title: string): CodegenTypeMap['Project'] => {
  const snakeTitle = _.kebabCase(title)

  // TODO: What a mess, type this without all the hacks
  return {
    ...testNodeId('Project'),
    isFirstTimeCT: true,
    isFirstTimeE2E: true,
    projectId: `${snakeTitle}-id`,
    title,
    projectRoot: `/usr/local/dev/projects/${snakeTitle}`,
    specs: {
      pageInfo: {
        __typename: 'PageInfo',
        hasNextPage: true,
        hasPreviousPage: false,
      },
      __typename: 'SpecConnection' as const,

Review comment (suggestion):
I think w can just copy paste this json file into the project, not sure we want to import from the existing desktop-gui to here (since that will prob `rm -rf` in the future).

Code after:
import _ from 'lodash'
import { randomComponents } from '../../../src/graphql/specs/testStubSpecs'
import config from '../../fixtures/config.json'

import type {
  Project,
  CodegenTypeMap,
} from '../generated/test-graphql-types.gen'
import { MaybeResolver, testNodeId } from './clientTestUtils'

export const createTestProject = (title: string): CodegenTypeMap['Project'] => {
  const snakeTitle = _.kebabCase(title)

  // TODO: What a mess, type this without all the hacks
  return {
    ...testNodeId('Project'),
    isFirstTimeCT: true,
    isFirstTimeE2E: true,
    projectId: `${snakeTitle}-id`,
    title,
    projectRoot: `/usr/local/dev/projects/${snakeTitle}`,
    specs: {
      pageInfo: {
        __typename: 'PageInfo',
        hasNextPage: true,
        hasPreviousPage: false,
      },
      __typename: 'SpecConnection' as const,
Repository: cypress-io/cypress
File: packages/graphql/schemas/schema.graphql (GraphQL)

Code before:
  """
  Given the current state, returns whether the user progress to the next step of the wizard
  """
  canNavigateForward: Boolean!

  """Whether the plugins for the selected testing type has been initialized"""
  chosenTestingTypePluginsInitialized: Boolean!

  """The title of the page, given the current step of the wizard"""
  description: String
  framework: WizardFrontendFramework

  """All of the component testing frameworks to choose from"""
  frameworks: [WizardFrontendFramework!]!

  """Whether we have chosen manual install or not"""
  isManualInstall: Boolean!
  language: WizardCodeLanguage

  """
  A list of packages to install, null if we have not chosen both a framework and bundler
  """
  packagesToInstall: [WizardNpmPackage!]

  """Configuration file based on bundler and framework of choice"""
  sampleCode(lang: WizardCodeLanguageLitteral! = js): String

  """IndexHtml file based on bundler and framework of choice"""
  sampleTemplate: String
  step: WizardStep!
  storybook: Storybook

  """
  The testing type we are setting in the wizard, null if this has not been chosen
  """
  testingType: TestingTypeEnum
  testingTypes: [TestingTypeInfo!]!

  """The title of the page, given the current step of the wizard"""
  title: String
}

"""Wizard bundler"""
type WizardBundler implements Node {
  """Relay style Node ID field for the WizardBundler field"""
  id: ID!

  """Whether this is the selected framework bundler"""
  isSelected: Boolean

  """Display name of the bundler"""

Review comment (suggestion):
```suggestion
  sampleCode(lang: WizardCodeLanguageLiteral! = js): String
```

Code after:

enum TestingTypeEnum {
  component
  e2e
}

type TestingTypeInfo implements Node {
  description: String!

  """Relay style Node ID field for the TestingTypeInfo field"""
  id: ID!
  title: String!
  type: TestingTypeEnum!
}

"""
The Wizard is a container for any state associated with initial onboarding to Cypress
"""
type Wizard {
  """All of the bundlers to choose from"""
  allBundlers: [WizardBundler!]!

  """All of the languages to choose from"""
  allLanguages: [WizardCodeLanguage!]!
  bundler: WizardBundler

  """
  Given the current state, returns whether the user progress to the next step of the wizard
  """
  canNavigateForward: Boolean!

  """Whether the plugins for the selected testing type has been initialized"""
  chosenTestingTypePluginsInitialized: Boolean!

  """The title of the page, given the current step of the wizard"""
  description: String
  framework: WizardFrontendFramework

  """All of the component testing frameworks to choose from"""
  frameworks: [WizardFrontendFramework!]!

  """Whether we have chosen manual install or not"""
  isManualInstall: Boolean!
  language: WizardCodeLanguage

  """
  A list of packages to install, null if we have not chosen both a framework and bundler
  """
  packagesToInstall: [WizardNpmPackage!]

  """Configuration file based on bundler and framework of choice"""
Repository: cypress-io/cypress
File: packages/graphql/src/schemaTypes/objectTypes/gql-WizardCodeLanguage.ts (TypeScript)

Code before:
import { objectType } from 'nexus'
import { CodeLanguageEnum } from '../enumTypes/gql-WizardEnums'

export const WizardCodeLanguage = objectType({
  name: 'WizardCodeLanguage',
  description: 'A code language that user can choose from to create their cypress.config',
  node: 'type',
  definition (t) {
    t.nonNull.field('type', {
      type: CodeLanguageEnum,
      description: 'The key of the language',
    })

    t.nonNull.boolean('isSelected', {
      description: 'Whether this is the selected language in the wizard',
      resolve: (source, args, ctx) => ctx.wizardData.chosenLanguage === source.type,
    })

    t.nonNull.string('name', {
      description: 'The name of the language',
    })
  },
  sourceType: {
    module: '@packages/types',
    export: 'CodeLanguage',
  },
})


Review comment (suggestion):
```suggestion
  description: 'A code language that the user can choose from to create their cypress.config',
```

Code after:
import { objectType } from 'nexus'
import { CodeLanguageEnum } from '../enumTypes/gql-WizardEnums'

export const WizardCodeLanguage = objectType({
  name: 'WizardCodeLanguage',
  description: 'A code language that the user can choose from to create their cypress.config',
  node: 'type',
  definition (t) {
    t.nonNull.field('type', {
      type: CodeLanguageEnum,
      description: 'The key of the language',
    })

    t.nonNull.boolean('isSelected', {
      description: 'Whether this is the selected language in the wizard',
      resolve: (source, args, ctx) => ctx.wizardData.chosenLanguage === source.type,
    })

    t.nonNull.string('name', {
      description: 'The name of the language',
    })
  },
  sourceType: {
    module: '@packages/types',
    export: 'CodeLanguage',
  },
})
Repository: cypress-io/cypress
File: packages/launchpad/src/components/select/SelectLanguage.spec.tsx (TypeScript)

Code before:
    type: 'js' as CodeLanguageEnum,
  },
  {
    id: 'ts',
    name: 'TypeScript',
    isSelected: false,
    type: 'ts' as CodeLanguageEnum,
  },
]

describe('<SelectLanguage />', () => {
  it('playground', () => {
    cy.mount(() => (
      <div class="m-10">
        <Select
          name="Language"
          options={manyOptions}
          value="js"
        />
      </div>
    ))

    cy.contains('Button', 'JavaScript').should('exist')
  })

  it('changes the language whan clicking', () => {
    const val = ref('js')

    cy.mount(() => (
      <div class="m-10">
        <Select
          name="Language"
          options={manyOptions}
          value={val.value}
          onSelect={(newVal) => {
            val.value = newVal
          }}
        />
      </div>
    ))

    cy.contains('Button', 'TypeScript').click().then(() => {
      expect(val.value).to.equal('ts')
    })
  })
})


Review comment (suggestion):
```suggestion
  it('changes the language when clicking', () => {
```

Code after:
    type: 'js' as CodeLanguageEnum,
  },
  {
    id: 'ts',
    name: 'TypeScript',
    isSelected: false,
    type: 'ts' as CodeLanguageEnum,
  },
]

describe('<SelectLanguage />', () => {
  it('playground', () => {
    cy.mount(() => (
      <div class="m-10">
        <Select
          name="Language"
          options={manyOptions}
          value="js"
        />
      </div>
    ))

    cy.contains('Button', 'JavaScript').should('exist')
  })

  it('changes the language when clicking', () => {
    const val = ref('js')

    cy.mount(() => (
      <div class="m-10">
        <Select
          name="Language"
          options={manyOptions}
          value={val.value}
          onSelect={(newVal) => {
            val.value = newVal
          }}
        />
      </div>
    ))

    cy.contains('Button', 'TypeScript').click().then(() => {
      expect(val.value).to.equal('ts')
    })
  })
})
Repository: cypress-io/cypress
File: packages/app/src/pages/NewSpec.vue (Vue)

Code before:
<template>
  <div v-if="query.data.value?.wizard.storybook">
    <h2>New Spec</h2>
    <ul v-if="stories.length">
      <li
        v-for="story of stories"
        :key="story.relative"
        @click="storyClick(story.absolute)"
      >
        <span class="text-indigo-600 font-medium">{{ story.fileName }}</span>
        <span class="font-light text-gray-400">{{ story.fileExtension }}</span>
        <span class="font-light text-gray-400 pl-16px show-on-hover">{{ story.relativeFromProjectRoot }}</span>
      </li>
    </ul>
    <p v-else>
      No Stories Detected
    </p>
  </div>
  <div v-else>
    Storybook is not configured for this project
  </div>
</template>
<route>
{
  name: "New Spec Page"
}
</route>
<script lang="ts" setup>
import { gql, useMutation, useQuery } from '@urql/vue'

Review comment (suggestion):
No need for the `v-if` conditional - if there's no elements in the array, it just won't show anything.

Code after:
<template>
  <div v-if="query.data.value?.app.activeProject?.storybook">
    <h2>New Spec</h2>
    <ul>
      <li
        v-for="story of stories"
        :key="story.relative"
        class="group"
        @click="storyClick(story.absolute)"
      >
        <span class="text-indigo-600 font-medium">{{ story.fileName }}</span>
        <span class="font-light text-gray-400">{{ story.fileExtension }}</span>
        <span class="font-light text-gray-400 pl-16px hidden group-hover:inline">{{ story.relativeFromProjectRoot }}</span>
      </li>
    </ul>
  </div>
  <div v-else>
    Storybook is not configured for this project
  </div>
</template>
<route>
{
  name: "New Spec Page"
}
</route>
<script lang="ts" setup>
import { gql, useMutation, useQuery } from '@urql/vue'
import { computed } from 'vue'
import { NewSpecQueryDocument, NewSpec_GenerateSpecFromStoryDocument } from '../generated/graphql'
Repository: cypress-io/cypress
File: packages/app/src/pages/NewSpec.vue (Vue)

Code before:
const query = useQuery({ query: NewSpecQueryDocument })
const mutation = useMutation(NewSpec_GenerateSpecFromStoryDocument)

async function storyClick (story: string) {
  await mutation.executeMutation({ storyPath: story })
  const generatedSpec = mutation.data.value?.generateSpecFromStory.storybook?.generatedSpec

  // Runner doesn't pick up new file without timeout, I'm guessing a race condition between file watcher and runner starting
  setTimeout(() => {
    window.location.href = `${window.location.origin}/__/#/tests/component/${generatedSpec}`
  }, 500)
}

const stories = computed(() => {
  return query.data.value?.wizard.storybook?.stories.map((story) => {
    return {
      ...story,
      fileExtension: story.baseName.replace(story.fileName, ''),
      relativeFromProjectRoot: story.relative.replace(story.baseName, ''),
    }
  }) || []
})

</script>

<style>
.show-on-hover {
  display: none;
}
li:hover .show-on-hover {
  display: inline;
}
</style>


Review comment (refactor):
Can we use the Windi CSS helpers where possible? Should be able do all this with the display helpers: https://windicss.org/utilities/display.html

Code after:

gql`
mutation NewSpec_GenerateSpecFromStory($storyPath: String!) {
  generateSpecFromStory (storyPath: $storyPath) {
    storybook {
      generatedSpec
    }
  }
} 
`

const query = useQuery({ query: NewSpecQueryDocument })
const mutation = useMutation(NewSpec_GenerateSpecFromStoryDocument)

async function storyClick (story: string) {
  await mutation.executeMutation({ storyPath: story })
  const generatedSpec = mutation.data.value?.generateSpecFromStory.storybook?.generatedSpec

  // Runner doesn't pick up new file without timeout, I'm guessing a race condition between file watcher and runner starting
  setTimeout(() => {
    window.location.href = `${window.location.origin}/__/#/tests/component/${generatedSpec}`
  }, 500)
}

const stories = computed(() => {
  return query.data.value?.app.activeProject?.storybook?.stories?.edges.map(({ node: story }) => {
    return {
      ...story,
      fileExtension: story.baseName.replace(story.fileName, ''),
      relativeFromProjectRoot: story.relative.replace(story.baseName, ''),
    }
  }) || []
})

</script>
Repository: cypress-io/cypress
File: packages/graphql/src/schemaTypes/objectTypes/gql-Storybook.ts (TypeScript)

Code before:
    })

    t.nonNull.string('baseName', {
      description: 'Full name of spec file (e.g. MySpec.test.tsx) without the spec extension',
    })

    t.nonNull.string('name', {
      description: 'Full name of spec file (e.g. MySpec.test.tsx)',
    })

    t.nonNull.string('fileName', {
      description: `The first part of the file, without extensions (e.g. MySpec)`,
    })
  },
})

export const Storybook = objectType({
  name: 'Storybook',
  description: 'Storybook',
  node: 'storybookRoot',
  definition (t) {
    t.nonNull.string('storybookRoot', {
      description: 'Folder containing storybook configuration files',
    })

    t.nonNull.list.nonNull.field('stories', {
      type: FileParts,
      description: 'List of all Storybook stories',
      resolve: async (source, args, ctx) => {
        return ctx.storybook.getStories()
      },
    })

    t.string('generatedSpec', {
      description: 'Most recent generated spec',
      resolve: (source, args, ctx) => ctx.wizardData.generatedSpec?.relative ?? null,
    })
  },
})


Review comment (suggestion):
We may want to consider representing stories as a `Connection`, much like specs:

https://github.com/cypress-io/cypress/blob/unified-desktop-gui/packages/graphql/src/schemaTypes/objectTypes/gql-Project.ts#L61-L67

Resources:
- Pagination using connections: https://graphql.org/learn/pagination/
- GraphQL Nexus Connection plugin: https://nexusjs.org/docs/plugins/connection

It would be pretty simple I think, just copy how specs is set up - then you get free pagination! 

Code after:
    })

    t.nonNull.string('baseName', {
      description: 'Full name of spec file (e.g. MySpec.test.tsx) without the spec extension',
    })

    t.nonNull.string('name', {
      description: 'Full name of spec file (e.g. MySpec.test.tsx)',
    })

    t.nonNull.string('fileName', {
      description: `The first part of the file, without extensions (e.g. MySpec)`,
    })
  },
})

export const Storybook = objectType({
  name: 'Storybook',
  description: 'Storybook',
  node: 'storybookRoot',
  definition (t) {
    t.nonNull.string('storybookRoot', {
      description: 'Folder containing storybook configuration files',
    })

    t.connectionField('stories', {
      type: FileParts,
      description: 'List of all Storybook stories',
      nodes: (source, args, ctx) => {
        return ctx.storybook.getStories()
      },
    })

    t.string('generatedSpec', {
      description: 'Most recent generated spec',
      resolve: (source, args, ctx) => ctx.wizardData.generatedSpec?.relative ?? null,
    })
  },
})