Nuxt Ava 端到端测试存储配置

Ale*_*sky 5 ava vuex vuejs2 nuxt.js

给出使用 Ava 的官方 Nuxt 端到端测试示例示例

import test from 'ava'
import { Nuxt, Builder } from 'nuxt'
import { resolve } from 'path'

// We keep a reference to Nuxt so we can close
// the server at the end of the test
let nuxt = null

// Init Nuxt.js and start listening on localhost:4000
test.before('Init Nuxt.js', async t => {
  const rootDir = resolve(__dirname, '..')
  let config = {}
  try { config = require(resolve(rootDir, 'nuxt.config.js')) } catch (e) {}
  config.rootDir = rootDir // project folder
  config.dev = false // production build
  config.mode = 'universal' // Isomorphic application
  nuxt = new Nuxt(config)
  await new Builder(nuxt).build()
  nuxt.listen(4000, 'localhost')
})

// Example of testing only generated html
test('Route / exits and render HTML', async t => {
  let context = {}
  const { html } = await nuxt.renderRoute('/', context)
  t.true(html.includes('<h1 class="red">Hello world!</h1>'))
})

// Close the Nuxt server
test.after('Closing server', t => {
  nuxt.close()
})
Run Code Online (Sandbox Code Playgroud)

如何使用NuxtBuilder来配置/访问应用程序 Vuex商店?示例 Vuex 商店看起来像:

import Vuex from "vuex";

const createStore = () => {
  return new Vuex.Store({
    state: () => ({
      todo: null
    }),
    mutations: {
      receiveTodo(state, todo) {
        state.todo = todo;
      }
    },
    actions: {
      async nuxtServerInit({ commit }, { app }) {
        console.log(app);
        const todo = await app.$axios.$get(
          "https://jsonplaceholder.typicode.com/todos/1"
        );
        commit("receiveTodo", todo);
      }
    }
  });
};

export default createStore;
Run Code Online (Sandbox Code Playgroud)

当前正在尝试运行提供的 Ava 测试,导致尝试访问@nuxtjs/axios方法 $get 时出错:

TypeError {
  message: 'Cannot read property \'$get\' of undefined',
}
Run Code Online (Sandbox Code Playgroud)

我可以在 Vuex 存储方法中模拟$get甚至$axios可用,我只需要了解如何在测试配置中访问。appnuxtServerInitapp

感谢您提供任何帮助。

Aud*_*tus 2

刚刚遇到这个问题,在研究了这么多教程之后,我拼凑了一个解决方案。

\n

以编程方式使用 vuex 存储时,您实际上已将其导入 Nuxt 中。这是通过以下方式完成的:

\n
    \n
  1. 导入 Nuxt 的配置文件
  2. \n
  3. 添加到配置以关闭除启用商店之外的所有其他内容
  4. \n
  5. 加载 Nuxt 实例并继续测试
  6. \n
\n

这是一个工作代码(假设您的 ava 和依赖项已设置)

\n

\r\n
\r\n
// For more info on why this works, check this aweomse guide by this post in getting this working\n// https://medium.com/@brandonaaskov/how-to-test-nuxt-stores-with-jest-9a5d55d54b28\nimport test from \'ava\'\nimport jsdom from \'jsdom\'\nimport { Nuxt, Builder } from \'nuxt\'\nimport nuxtConfig from \'../nuxt.config\' // your nuxt.config \n\n// these boolean switches turn off the build for all but the store\nconst resetConfig = {\n  loading: false,\n  loadingIndicator: false,\n  fetch: {\n    client: false,\n    server: false\n  },\n  features: {\n    store: true,\n    layouts: false,\n    meta: false,\n    middleware: false,\n    transitions: false,\n    deprecations: false,\n    validate: false,\n    asyncData: false,\n    fetch: false,\n    clientOnline: false,\n    clientPrefetch: false,\n    clientUseUrl: false,\n    componentAliases: false,\n    componentClientOnly: false\n  },\n  build: {\n    indicator: false,\n    terser: false\n  }\n}\n\n// We keep a reference to Nuxt so we can close\n// the server at the end of the test\nlet nuxt = null\n\n// Init Nuxt.js and start listening on localhost:5000 BEFORE running your tests. We are combining our config file with our resetConfig using Object.assign into an empty object {}\ntest.before(\'Init Nuxt.js\', async (t) => {\n  t.timeout(600000)\n  const config = Object.assign({}, nuxtConfig, resetConfig, {\n    srcDir: nuxtConfig.srcDir, // don\'t worry if its not in your nuxt.config file. it has a default\n    ignore: [\'**/components/**/*\', \'**/layouts/**/*\', \'**/pages/**/*\']\n  })\n  nuxt = new Nuxt(config)\n  await new Builder(nuxt).build()\n  nuxt.listen(5000, \'localhost\')\n})\n\n// Then run our tests using the nuxt we defined initially\ntest.serial(\'Route / exists and renders correct HTML\', async (t) => {\n  t.timeout(600000) // Sometimes nuxt\'s response is slow. We increase the timeont to give it time to render\n  const context = {}\n  const { html } = await nuxt.renderRoute(\'/\', context)\n  t.true(html.includes(\'preload\'))\n  // t.true(true)\n})\n\ntest.serial(\'Route / exits and renders title\', async (t) => {\n  t.timeout(600000)\n  const { html } = await nuxt.renderRoute(\'/\', {})\n  const { JSDOM } = jsdom // this was the only way i could get JSDOM to work. normal import threw a functione error\n  const { document } = (new JSDOM(html)).window\n  t.true(document.title !== null && document.title !== undefined) // simple test to check if site has a title\n})
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n

这样做应该有效。但是,您仍然可能会遇到一些错误

\n
    \n
  • \xe2\x9c\x96 运行测试时超时。如果你得到了这个,那你就运气不好了。我认为问题出在 Ava 身上,因为它没有给出描述性错误(并且删除任何 Nuxt 方法似乎可以修复它),但到目前为止,即使使用上面的代码片段,有时它可以工作,有时却不能。
  • \n
  • 我此时最好的猜测是,Nuxt 方面使用renderRouterrenderAndGetWindowava 不会等待,但是在尝试这些方法中的任何一个时,ava 几乎立即“超时”,尽管 t.timeout 是为每个测试明确设置。到目前为止,我的研究已经引导我检查超时renderAndGetWindow(如果存在,但文档没有指出)。
  • \n
\n

这就是我所拥有的一切。

\n