与Nuxt和Jest进行集成测试

时间:2018-09-25 07:55:51

标签: jasmine jestjs nuxt.js

我希望使用Nuxt的renderAndGetWindow渲染页面,以便测试我的API返回的值。

这是我的方法:

// Nuxt instance
let nuxt = null;
// Our page to test
let homePage = null;

beforeAll(async (done) => {
    // Configuration
    const rootDir = resolve(__dirname, '../..');
    let config = {};
    config = require(resolve(rootDir, 'nuxt.config.js'));
    config.rootDir = rootDir; // project folder
    config.env.isDev = false; // dev build
    config.mode = 'universal'; // Isomorphic application

    nuxt = new Nuxt(config);
    await new Builder(nuxt).build();
    nuxt.listen(3001, 'localhost');
    homePage = await nuxt.renderAndGetWindow('http://localhost:3001/');
  });

这给了我2个明显的错误:

  

console.error node_modules / jest-jasmine2 / build / jasmine / Env.js:157       未处理的错误

     

console.error node_modules / jest-jasmine2 / build / jasmine / Env.js:158       TypeError:setInterval(...)。unref不是函数

  

超时-在jest.setTimeout指定的5000ms超时内未调用异步回调。

 at mapper (node_modules/jest-jasmine2/build/queue_runner.js:41:52)

自从Ava切换到Jest之后,我就知道了。

我处理渲染错误吗?

1 个答案:

答案 0 :(得分:1)

取消引用

The default test environment for Jest is a browser-like environment through jsdom

unrefNode提供的特殊功能。不是在浏览器或jsdom中实现,而是在it is implemented in the "node" test environment in Jest中实现。

测试Nuxt应用程序看起来既需要Node环境来启动服务器,又需要jsdom环境来测试结果UI。

这可以通过在测试设置过程中将测试环境设置为“节点”并使用window初始化jsdom来完成。

超时

Jest"wait if you provide an argument to the test function, usually called done"。这适用于测试功能和设置功能,例如beforeAll

您的beforeAll函数具有一个从未调用过的参数doneJest将等待,直到调用done或使用jest.setTimeout配置的超时(默认为5秒)。

您正在使用async函数,并且在该函数的异步部分上使用了await,因此您不需要done。将您的beforeAll函数更改为不带任何参数,这将阻止Jest等待调用done

在我的测试中,启动Nuxt服务器需要花费一段时间,因此您可以将timeout值作为附加参数传递给beforeAll,以增加该函数的超时时间。


这是具有以下更改的更新测试:

/**
 * @jest-environment node
 */
// TODO: Set the environment to "node" in the Jest config and remove this docblock

// TODO: Move this to a setup file
const { JSDOM } = require('jsdom');
const { window } = new JSDOM();  // initialize window using jsdom

const resolve = require('path').resolve;
const { Nuxt, Builder } = require('nuxt');

// Nuxt instance
let nuxt = null;
// Our page to test
let homePage = null;

beforeAll(async () => {
  // Configuration
  const rootDir = resolve(__dirname, '../..');
  let config = {};
  config = require(resolve(rootDir, 'nuxt.config.js'));
  config.rootDir = rootDir; // project folder
  config.env.isDev = false; // dev build
  config.mode = 'universal'; // Isomorphic application

  nuxt = new Nuxt(config);
  await new Builder(nuxt).build();
  nuxt.listen(3001, 'localhost');
  homePage = await nuxt.renderAndGetWindow('http://localhost:3001/');
}, 20000);  // Give the beforeAll function a large timeout

afterAll(() => {
  nuxt.close();
});

describe('homepage', () => {
  it('should do something', () => {
  });
});