mocha 테스트에서 웹 팩에일리어스 사용
React/Redux/Webpack에서 웹 앱을 개발하고 있으며, 현재 Mocha와의 테스트를 통합하고 있습니다.
Redux 설명서의 테스트 기술 지침을 따랐지만 웹 팩 별칭에 문제가 발생했습니다.
예를 들어, 작업 작성자 중 한 명을 위해 이 테스트의 Imports 섹션을 확인하십시오.
import expect from 'expect' // resolves without an issue
import * as actions from 'actions/app'; // can't resolve this alias
import * as types from 'constants/actionTypes'; // can't resolve this alias
describe('Actions', () => {
describe('app',() => {
it('should create an action with a successful connection', () => {
const host = '***************',
port = ****,
db = '******',
user = '*********',
pass = '******';
const action = actions.createConnection(host, port, db, user, pass);
const expectedAction = {
type: types.CREATE_CONNECTION,
status: 'success',
payload: { host, port, database, username }
};
expect(action).toEqual(expectedAction);
});
});
});
코멘트에서 알 수 있듯이, mocha는 에일리어스된 의존관계를 참조할 때 Import 스테이트먼트를 해결할 수 없습니다.
저는 아직 웹 팩을 처음 접하기 때문에webpack.config.js
:
module.exports = {
devtool: 'eval-source-map',
entry: [
'webpack-hot-middleware/client',
'./src/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
resolve: {
extensions : ['', '.js', '.jsx'],
alias: {
actions: path.resolve(__dirname, 'src', 'actions'),
constants: path.resolve(__dirname, 'src', 'constants'),
/* more aliases */
}
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
exclude: /node_modules/,
include: __dirname
}]
}
};
또한 명령어를 사용하고 있습니다.npm test
mocha를 실행하기 위해 사용하는 스크립트는 다음과 같습니다.package.json
.
{
"scripts": {
"test": "mocha ./src/**/test/spec.js --compilers js:babel-core/register --recursive"
}
}
그래서 내가 막힌 곳이 여기야.웹 팩을 실행할 때 모카에 가명을 포함해야 합니다.
좋아요, 그래서 깨달았어요 제가 애일리어스 했던 모든 것들이src/
전화번호부를 수정하기만 하면 됩니다.npm run test
대본.
{
"scripts": {
"test": "NODE_PATH=./src mocha ./src/**/test/spec.js --compilers js:babel-core/register --recursive"
}
}
모두에게 먹히진 않겠지만 내 문제는 해결됐어
내가 작성한 babel 플러그인을 사용할 수도 있습니다.https://github.com/trayio/babel-plugin-webpack-alias 이것은 당신의 babel 플러그 인을 포함시키는 것만으로 당신의 aliased 경로를 상대 경로로 변환합니다..babelrc
.
저도 같은 문제가 있었습니다만, 이 플러그인으로 해결했습니다.
https://www.npmjs.com/package/babel-plugin-webpack-aliases
"mocha"의 실행 명령어가 읽혀지지 않았습니다.webpack.config.js
에일리어스를 해결할 수 없습니다.
이 플러그인을 설정함으로써 다음 사항을 고려하십시오.webpack.config.js
"babel-core/register"를 사용하여 컴파일할 때 사용합니다.그 결과 에일리어스는 테스트 중에도 유효합니다.
npm i -D babel-plugin-webpack-aliases
이 설정을 에 추가합니다..babelrc
{
"plugins": [
[ "babel-plugin-webpack-aliases", { "config": "./webpack.config.js" } ]
]
}
이 문제를 해결한 것 같아요.mock-require와 proxyquire의 2가지 패키지를 사용해야 합니다.
다음과 같은 js 파일이 있다고 가정합니다.
app.module
import action1 from 'actions/youractions';
export function foo() { console.log(action1()) };
테스트 코드는 다음과 같습니다.
app.test.module
import proxyquire from 'proxyquire';
import mockrequire from 'mock-require';
before(() => {
// mock the alias path, point to the actual path
mockrequire('actions/youractions', 'your/actual/action/path/from/your/test/file');
// or mock with a function
mockrequire('actions/youractions', {actionMethod: () => {...}));
let app;
beforeEach(() => {
app = proxyquire('./app', {});
});
//test code
describe('xxx', () => {
it('xxxx', () => {
...
});
});
파일 트리
app.js
|- test
|- app.test.js
먼저 mock-require in before 함수에 의한 에일리어스 패스의 모킹과 프록시 쿼리에 의한 각 함수에 의한 테스트 오브젝트의 모킹입니다.
대니의 대답은 훌륭하다.하지만 제 상황은 조금 달라요.나는 웹팩을 사용했다.resolve.alias
아래의 모든 파일을 사용하다src
폴더입니다.
resolve: {
alias: {
'-': path.resolve(__dirname, '../src'),
},
},
자신의 모듈에는 다음과 같은 특별한 프레픽스를 사용합니다.
import App from '-/components/App';
이와 같은 코드를 테스트하려면 명령을 추가해야 합니다.ln -sf src test/alias/-
mocha 테스트 및 사용NODE_PATH=./test/alias
과 같습니다최종 스크립트는 다음과 같습니다.
{
"scripts": {
"test": "ln -sf src test/alias/-; NODE_PATH=./test/alias mocha ./src/**/test/spec.js --compilers js:babel-core/register --recursive"
}
}
PS:
하였습니다.-
글씨들이 있기 때문이다.@
★★★★★★★★★★★★★★★★★」~
충분히 안전하지 않습니다.나는 여기서 안전한 캐릭터에 대한 답을 찾았다.
내 생각엔 넌 아마--require babel-register
안에서mocha.opts
. babel module resolver 플러그인 https://github.com/tleunen/babel-plugin-module-resolver 을 사용할 수 있습니다.이것에 의해, Web 팩에일리어스와 같이, .babelrc 로 에일리어스를 설정할 수 있습니다.
{
"plugins": [
["module-resolver", {
"alias": {
"actions": "./src/actions",
"constants": "./src/constants"
}
}]
]
}
나도 똑같은 문제가 있었어.require.js 또는 노드의 요구에서 웹 팩 별칭을 사용하는 것은 불가능할 것 같습니다.
유닛 테스트에서 mock-require를 사용하여 다음과 같이 경로를 수동으로 교체했습니다.
var mock = require('mock-require');
mock('actions/app', '../../src/actions/app');
는 mock-drivate의 실제 하는 것이 수 도구입니다.대부분의 경우 실제 스크립트를 사용하는 대신 대부분의 의존관계를 조롱하고 싶기 때문입니다.src
.
를 한 config/webpack.common.js
resolve: {
alias: {
'~': path.resolve(__dirname, './../src/app')
}
}
그 후 babel-map-webpack-maps를 설치합니다.
npm i babel-plugin-webpack-alias --save-dev
후 리 then then then.babelrc
put :
{
"presets": ["env"],
"plugins": [
["babel-plugin-webpack-alias", {
"config": "./config/webpack.common.js" // path to your webpack config
}]
]
}
언급URL : https://stackoverflow.com/questions/33793504/using-webpack-aliases-in-mocha-tests
'programing' 카테고리의 다른 글
사이드바 외부에서 위젯을 사용하시겠습니까? (0) | 2023.02.27 |
---|---|
jQuery Ajax 함수의 전체 양식을 데이터로 전달합니다. (0) | 2023.02.27 |
WooCommerce:고객이 떠난 후 돌아올 때 체크아웃 정보를 유지하는 방법은 무엇입니까? (0) | 2023.02.27 |
사용자 지정 이벤트에서 angular-ui 도구 설명 사용 (0) | 2023.02.27 |
새로운 Facebook 앱 개발자에서 샌드박스 모드를 비활성화하려면 어떻게 해야 합니까? (0) | 2023.02.27 |