使用require模块进行Jest测试:ejs-loader

时间:2017-05-27 18:17:07

标签: node.js reactjs ejs jestjs

我正在尝试将大型静态html包加载到反应组件中,并在jsx中输入所有内容。我目前正在尝试使用ejs-loaderhtml-react-parser来评估此问题的可行性。实际上一切都很好,但我无法通过jest进行任何测试。

我从Cannot find module ejs-loader!./AboutPage.view.ejs错误收到AboutPage.js,我不确定该怎么做。

我目前正在处理react-slingshot作为我尝试此基础的基础。

该项目的回购是here

组件本身很简单:



import React from 'react';
import Parser from 'html-react-parser';
import '../styles/about-page.css';

const view = require('ejs-loader!./AboutPage.view.ejs')();

// Since this component is simple and static, there's no parent container for it.
const AboutPage = () => {
  return (
    <div>
      {Parser(view)}
    </div>
  );
};

export default AboutPage;
&#13;
&#13;
&#13;

测试是:

&#13;
&#13;
import React from 'react';
import {shallow} from 'enzyme';
import AboutPage from './AboutPage';

describe('<AboutPage />', () => {
  
  it('should have a header called \'About\'', () => {
    const wrapper = shallow(<AboutPage />);
    const actual = component.find('h2').text();
    const expected = 'About';

    expect(actual).toEqual(expected);
  });
  
});
&#13;
&#13;
&#13;

我已阅读the docs和类似问题this。我试图使用自定义变换器,但我可能会误解某些东西,因为它似乎甚至没有被称为。

的package.json

&#13;
&#13;
"jest": {
    "moduleNameMapper": {
      "\\.(css|scss)$": "identity-obj-proxy",
      "^.+\\.(gif|ttf|eot|svg|woff|woff2|ico)$": "<rootDir>/tools/fileMock.js"
    },
    "transform": {
      "^.+\\.js$": "babel-jest",
      "\\.(ejs|ejx)$": "<rootDir>/tools/ejx-loader/jest.transformer.js"
    }
  },
&#13;
&#13;
&#13;

和变压器本身:

&#13;
&#13;
module.exports = {
  process(src, filename, config, options){
    console.log('????');
    return 'module.exports = ' +  require(`ejs-loader!./${filename}`);
    //return require(`ejs-loader!./${filename}`);
  }
};
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

您可以尝试将模块名称映射器更改为 -

{ "\\.(css|scss)$": "identity-obj-proxy", "^.+\\.(gif|ttf|eot|svg|woff|woff2|ico)$": "<rootDir>/tools/fileMock.js" "ejs-loader!(.*)": "$1", }

这至少应该调用你的自定义变换器。

自定义变压器也应该是 -

const _ = require('lodash');
module.exports = {
  process(src, filename, config, options){
    console.log('????');
    return 'module.exports = ' +  _.template(src);
  }
};

答案 1 :(得分:0)

您似乎没有将.ejs指定为moduleFileExtension

"jest": {
  ...
  "moduleFileExtensions": ["js", "jsx", "ejs", "ejx"],
  ...
}

此外,ejs-loader将使用cjs语法为您导出函数,因此您可以在变换器中执行以下操作:

const loader = require('ejs-loader');

module.exports = {process: loader};

答案 2 :(得分:0)

为我工作:

"jest": {
  "moduleNameMapper": {
    '\\.(ejs|ejx)$': '<rootDir>/jest-ejs.transformer.js'
  },
  moduleFileExtensions: ['js', 'json', 'jsx', 'ejs']
},

jest-ejs.transformer.js

const loader = require('ejs-loader');
module.exports = {process: loader};