首页 > 解决方案 > 如何使用 cypress 导入夹具文件

问题描述

我正在写关于柏树夹具的文章。我正在尝试使用 fixture.incorrectEmail 和 fixture.incorrectPassword 但它不起作用。错误是无法读取correctEmail未定义的属性

我想如下使用它。

我的夹具文件 json:

{
  "incorrectEmail": "karolina.waterrr@gmail.com",
  "incorrectPassword": "1234777",
}

我的测试文件:

import fixture from '../../fixtures/data.json'

describe("checkAuthentication", () => {
    before(() => {
        cy.visit("http://localhost:8080")
    })
    it('it should fail if bad email', () => {
        cy.dataTestId("worker-email").type(fixture.incorrectEmail)
        cy.dataTestId("worker-password").type(fixture.incorrectPassword)
        cy.dataTestId("test-button").click()
        cy.dataTestId("test-wrong-message").should("have.text", " wrong email ")

    })

我的配置文件:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "es5",
      "dom"
    ],
    "types": [
      "cypress"
    ],
    "resolveJsonModule": true,
    "allowSyntheticDefaultImports": true,
  },
  "include": [
    "**/*.ts"
  ]
}

谢谢您的帮助,

导入是正确的,但是 console.log(fixture) 返回未定义,老实说我不知道​​出了什么问题

标签: javascriptcypress

解决方案


赛普拉斯提供了一种在测试中访问夹具文件的内置方法。您可以从赛普拉斯文档中了解更多信息。

describe('Test Suite', () => {

  before(function() {
    cy.visit("http://localhost:8080")
  })

  beforeEach(function() {
    cy.fixture('data').then((data) => {
      this.data = data
    })
  })

  it('Test', function() {
    cy.dataTestId("worker-email").type(this.data.incorrectEmail)
    cy.dataTestId("worker-password").type(this.data.incorrectPassword)
    cy.dataTestId("test-button").click()
    cy.dataTestId("test-wrong-message").should("have.text", " wrong email ")
  })
})

请记住,如果您使用this测试上下文对象存储和访问夹具数据,请确保使用function () { ... }回调。否则,测试引擎将不会将 this 指向测试上下文。


推荐阅读