执行登录命令并访问vuex store

Implement login command and access vuex store

我有一个登录过程,在向服务器发送请求并获得响应后,我这样做:

 this.$auth.setToken(response.data.token);
 this.$store.dispatch("setLoggedUser", {
     username: this.form.username
 });

现在我想在使用 cypress 进行测试时模拟这种行为,因此我不需要每次 运行 测试时都实际登录。

所以我创建了一个命令:

Cypress.Commands.add("login", () => {
  cy
    .request({
      method: "POST",
      url: "http://localhost:8081/api/v1/login",
      body: {},
      headers: {
        Authorization: "Basic " + btoa("administrator:12345678")
      }
    })
    .then(resp => {
      window.localStorage.setItem("aq-username", "administrator");
    });

});

但我不知道如何模拟 "setLoggedUser" 操作,知道吗?

在您创建 vuex store 的应用代码中,您可以有条件地将其公开给赛普拉斯:

const store = new Vuex.Store({...})

// Cypress automatically sets window.Cypress by default
if (window.Cypress) {
  window.__store__ = store
}

然后在你的 Cypress 测试代码中:

cy.visit()
// wait for the store to initialize
cy.window().should('have.property', '__store__')

cy.window().then( win => {
  win.__store__.dispatch('myaction')
})

您可以将其添加为另一个自定义命令,但确保您首先访问过您的应用程序,否则该 vuex 商店将不存在。

  • Step 1: Inside main.js provide the store to Cypress:
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

if (window.Cypress) {
  // Add `store` to the window object only when testing with Cypress
  window.store = store
}
  • Step 2: Inside cypress/support/commands.js add a new command:
Cypress.Commands.add('login', function() {
  cy.visit('/login') // Load the app in order `cy.window` to work
  cy.window().then(window => { // .then() to make cypress wait until window is available
    cy.wrap(window.store).as('store') // alias the store (can be accessed like this.store)
    cy.request({
      method: 'POST',
      url: 'https://my-app/api/auth/login',
      body: {
        email: 'user@gmail.com',
        password: 'passowrd'
      }
    }).then(res => {
      // You can access store here
      console.log(this.store)
    })
  })
})
  • Step 4: Inside cypress/integration create a new test
describe('Test', () => {
  beforeEach(function() {
    cy.login() // we run our custom command
  })

  it('passes', function() { // pass function to keep 'this' context
    cy.visit('/')
    // we have access to this.store in our test
    cy.wrap(this.store.state.user).should('be.an', 'object')
  })
})