how to filter out files during when ember-cli is building my app (filtering monaco's many files, specifically) - ember.js

I am trying to reduce monaco-editor dependency size.
I found this answer which shows how to do it on angular - by editing the glob configuration in angular.json file.
What is the corresponding file for this configuration on ember?
EDIT
I found this read me for configuring on ember-cli-build, any idea how to configure?
module.exports = function (defaults) {
const app = new EmberApp(defaults, {
autoImport: {
alias: {
'monaco-editor': '** what here? **',
},
},

I don't know how to read the angular comment there, but what I did was build my own copy of Monaco, with esbuild.
I am trying to reduce monaco-editor dependency size.
generally, if you're using embroider, if you don't import it, it won't be a part of your build.
This is probably more try-hard than you're looking for, but gives you more control over your assets.
here is my package where I do that: https://github.com/NullVoxPopuli/limber/tree/main/packages/monaco
I use this build script:
'use strict';
const path = require('path');
const os = require('os');
const fs = require('fs').promises;
const copy = require('recursive-copy');
const esbuild = require('esbuild');
const { esBuildBrowserTargets } = require('#nullvoxpopuli/limber-consts');
const OUTPUT_DIR = path.join(__dirname, 'dist').toString();
const ME = path.dirname(require.resolve('monaco-editor/package.json'));
const cssLocation = path.join(`${ME}/min/vs/editor`);
const workers = {
base: path.join(ME, 'esm/vs/editor/editor.main.js'),
editor: path.join(ME, 'esm/vs/editor/editor.worker.js'),
json: path.join(ME, 'esm/vs/language/json/json.worker.js'),
css: path.join(ME, 'esm/vs/language/css/css.worker.js'),
html: path.join(ME, 'esm/vs/language/html/html.worker.js'),
ts: path.join(ME, 'esm/vs/language/typescript/ts.worker.js'),
};
/**
* - Builds Web Workers
* - Builds a preconfigured bundle with monaco-editor
* - Copies tall relevant CSS to the same output folder
*/
module.exports = async function build() {
let buildDir = await fs.mkdtemp(path.join(os.tmpdir(), 'monaco--workers-'));
await esbuild.build({
loader: { '.ts': 'ts', '.js': 'js', '.ttf': 'file' },
entryPoints: [
workers.editor,
workers.json,
workers.css,
workers.html,
workers.ts,
workers.base,
],
bundle: true,
outdir: buildDir,
format: 'esm',
target: esBuildBrowserTargets,
minify: false,
sourcemap: false,
});
await esbuild.build({
loader: { '.ts': 'ts', '.js': 'js', '.ttf': 'file' },
entryPoints: [path.join('preconfigured', 'index.ts')],
bundle: true,
outfile: path.join(buildDir, 'preconfigured.js'),
format: 'esm',
target: esBuildBrowserTargets,
// something silly is going on with Monaco and esbuild
// TODO: report this to ESBuild's GitHub
minify: false,
sourcemap: false,
});
await copy(`${buildDir}`, OUTPUT_DIR, {
overwrite: true,
filter: ['**/*', '!*.nls.*'],
rename(filePath) {
if (filePath.includes('ttf')) {
return 'codicon.ttf';
}
return filePath;
},
});
await copy(`${cssLocation}`, OUTPUT_DIR, {
overwrite: 'inline',
filter: ['**/*.css'],
});
// TODO: how to change the monaco config to allow this to be in a `monaco/` folder
// const ICON_PATH = 'base/browser/ui/codicons/codicon/codicon.ttf';
// await copy(path.join(ME, 'esm/vs', ICON_PATH), ICON_PATH)
};
if (require.main === module) {
module.exports();
}
and then in my ember-cli-build.js here: https://github.com/NullVoxPopuli/limber/blob/main/frontend/ember-cli-build.js#L50
(merging the extraPublic Trees)
I invoke:
// Desktop Editor
require('#nullvoxpopuli/limber-monaco/broccoli-funnel')(),
the broccoli-funnel
'use strict';
const path = require('path');
const Funnel = require('broccoli-funnel');
const SRC_FILES = path.join(__dirname, 'dist');
/**
* This broccoli funnel is for copying the built assets to a target
* app's public folder. No building occurs
*
*/
module.exports = function monacoFunnel() {
return new Funnel(SRC_FILES, {
destDir: 'monaco/',
});
};
I then load monaco via a modifier like this:
import { assert } from '#ember/debug';
import type { Args } from './-types';
/**
* I wish there was a way to specify types-only packages
* while Limber uses Monaco, it's provided by the limber-monaco
* broccoli funnel (copied into the public folder).
*
* So the devDep on monaco-editor in limber/frontend is *solely*
* for the type defs
*/
import type * as monaco from 'monaco-editor';
export default function installMonaco(element: HTMLElement, ...[value, updateText, named]: Args) {
assert(`Expected MONACO to exist`, MONACO);
element.innerHTML = '';
let { editor, setText } = MONACO(element, value, updateText, named);
named.setValue((text) => {
// changing the text this ways calls updateText for us
// updateText(text); // update the service / URL
setText(text); // update the editor
});
return () => editor?.dispose();
}
let MONACO:
| undefined
| ((
element: HTMLElement,
...args: Args
) => { editor: monaco.editor.IStandaloneCodeEditor; setText: (text: string) => void });
export async function setupMonaco() {
if (MONACO) return;
// TypeScript doesn't have a way to type files in the public folder
// eslint-disable-next-line #typescript-eslint/ban-ts-comment
// #ts-ignore
MONACO = (await import(/* webpackIgnore: true */ '/monaco/preconfigured.js')).default;
}
and usage:
import monacoModifier from './my-monaco-modifier';
export default class Demo extends Component {
monaco = monacoModifier
}
<div {{this.monaco}}></div>
You can view this in action here: https://limber.glimdown.com/

I solved the issue by skipping languages import (which I don't need since I use custom language.
adding the following under webpackConfig:
new MonacoWebpackPlugin({
languages: [],
}),
Here is the full config in ember-cli-build.js:
return require('#embroider/compat').compatBuild(app, Webpack, {
staticAddonTestSupportTrees: true,
staticAddonTrees: true,
staticHelpers: true,
// staticComponents: true,
onOutputPath(outputPath) {
writeFileSync(join(__dirname, '.embroider-app-path'), outputPath, 'utf8');
},
packagerOptions: {
webpackConfig: {
module: {
rules: [
{
test: /\.(png|jpg|gif|svg|woff|woff2|eot|ttf|otf|flac)$/i,
loader: 'file-loader',
options: {
name: '[path][name]-[contenthash].[ext]',
},
},
],
},
plugins: [
new MonacoWebpackPlugin({
languages: [],
}),
],
},
},
});

Related

Webpack chunks larger when building for production

When executing Webpack 4 for development and production mode the chunks for development are smaller than when built for production. I am currently using the following Webpack 4 configuration;
const webpack = require('webpack');
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const DuplicatePackageCheckerPlugin = require('#cerner/duplicate-package-checker-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const bundleAnalyzerPlugin = new BundleAnalyzerPlugin();
/** ignore #anwb packages
* Keep warning for multiple react-is versions as warning
* * */
const duplicatePackageChecker = new DuplicatePackageCheckerPlugin({
verbose: true,
exclude(instance) {
// ignore #anwb packages
if (instance.name.includes('#anwb')) {
return true;
}
return false;
},
});
/** clean dist on build , webpack 5 supports clean property in output object * */
const cleanWebpackPlugin = new CleanWebpackPlugin();
module.exports = (env, argv) => {
const isDevelopment = argv.mode === 'development';
// No sourcemaps in production
// const devtool = isDevelopment ? { devtool: 'source-map' } : {};
const devtool = { devtool: 'source-map' };
// Separated output folders for OTA an P to separate artifacts in pipeline
const distFolder = isDevelopment ? 'distota' : 'dist';
console.log(`Webpack build for : ${isDevelopment ? 'development' : 'production'}`);
console.log(`Source maps included : ${Object.keys(devtool).length !== 0 ? 'yes' : 'no'}`);
console.log(`Build directory : ${distFolder}`);
return {
entry: {
index: path.resolve(__dirname, './src/index.tsx'),
},
/**
* Library target is set to umd so the anwb core js loading system can import it
*/
output: {
path: path.resolve(__dirname, `./${distFolder}`),
filename: '[name].js',
chunkFilename: '[name].js',
libraryTarget: 'umd',
publicPath: `/`,
},
resolve: {
/**
* Import files from the src or node_modules directory
*/
modules: ['src', 'node_modules'],
/**
* Load preact-compat when react is encountered
*/
alias: {
react: 'preact/compat',
'react-dom': 'preact/compat',
'#anwb/typography': path.resolve(__dirname, '.', 'node_modules', '#anwb/typography'),
},
extensions: ['.ts', '.tsx', '.js'],
},
bail: true,
/**
* Include source maps
*/
...devtool,
module: {
rules: [
/**
* The font is loaded using the fileloader and placed in a fonts folder
*/
{
test: /\.(eot|ttf|woff|woff2)$/,
loader: 'file-loader',
options: {
name: 'fonts/[name].[ext]',
},
},
/**
* The svg images are loaded and placed in the images directory
*/
{
test: /\.svg$/,
loader: 'file-loader',
options: {
name: 'images/[name][hash].[ext]',
},
},
/**
* All images bigger then 25000 bytes are placed in an images folder. Small images are included as inline base 64.
*/
{
test: /\.(png|jpg|gif)$/,
loader: 'url-loader',
options: {
limit: '25000',
name: 'images/[name][hash].[ext]',
},
},
/**
* All less files are converted down to css and are autoprefixed using the postcss module
*/
{
test: /\.(less|css)$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
{
loader: 'less-loader',
options: {
lessOptions: {
javascriptEnabled: true,
},
},
},
],
},
/**
* Js is transpiled using babel
*/
{
test: /\.(js|ts|tsx)$/,
exclude: ['/node_modules'],
include: [/src/, /node_modules\/#anwb/],
loader: 'babel-loader',
options: {
presets: [
[
'#babel/env',
{
modules: false,
targets: ['> 1% in NL', 'last 2 versions', 'last 5 iOS versions'],
// NewRelic uses Chrome 72 (2019). Therefore we need to Polyfill some features like Promise.allSettled.
// Story is made to remove it when NR is updated (MACS-13942)
useBuiltIns: 'usage',
corejs: { version: 3, proposals: true },
},
],
'#babel/react',
'#babel/flow',
],
plugins: [
['#babel/plugin-transform-react-jsx', { pragma: 'h' }],
'syntax-dynamic-import',
],
},
},
],
},
optimization: {
// splitChunks: {
// chunks: 'all',
// },
minimizer: [
new CssMinimizerPlugin({
test: /.css$/i,
minimizerOptions: {
preset: [
'default',
{
discardComments: { removeAll: true },
},
],
},
}),
new UglifyJsPlugin({
uglifyOptions: {
output: {
comments: false,
},
},
}),
],
},
plugins: [
bundleAnalyzerPlugin,
cleanWebpackPlugin,
/**
* The extract text plugin makes sure that all css is put into a single css file named after the application
*/
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[name].css',
}),
duplicatePackageChecker,
/**
* Dont use all moment locales
*/
new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /nl/),
new webpack.DefinePlugin({
// "process.env": {
// NODE_ENV: simulateProduction ? JSON.stringify("production") : JSON.stringify("development")
// },
PRODUCTION: true,
}),
],
};
};
E.g. if the build is created for development the component has a stat size of 203KB
If the same build is run for production the same component has a stat size of 676KB
When the Webpack optimization is removed, this does not change. So i can rule this out.
Webpack is started using the two following package.json scripts;
"build": "webpack --config ./webpack.js --mode=production",
"build:ota": "webpack --config ./webpack.js --mode=development",
Any ideas how to optimize the chunks for production ?

Build failure while using Webpack4 in AngularJS1.5.11

I am working on an AngularJS Project to configure webpack for bundling purpose. I am using webpack4 for the same.
Below is the config file.
webpack.config.js:
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');// Require html-webpack-plugin plugin
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const ExtractNormalCSS = new ExtractTextPlugin("./src/main/frontend/sass/main.scss");
const extractCSS = new ExtractTextPlugin('/src/main/frontend/assets/icons/paas-icons/style.css');
module.exports = {
entry: [ "./src/main/frontend/app/app.js","./src/main/frontend/sass/main.scss"], // webpack entry point. Module to start building dependency graph
output: {
path: path.join(__dirname, '/distTemp/'), // Folder to store generated bundle
filename: '[name].bundle.js' // Name of generated bundle after build
//publicPath: '' // public URL of the output directory when referenced in a browser
},
resolve:{
modules: [
'node_modules',
'bower_components',
'src'
],
extensions:[".js"]
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
options: {
compact: false,
cacheDirectory: true,
presets: ['es2015', 'angular'],
},
},
{
test: /.(scss)$/,
loader: 'style-loader!css-loader!sass-loader'
},
{
test: /\.html$/,
loader: 'html-loader?name=views/[name].[ext]'
},
{
test: /\.(png|jpg)$/,
use: [
'url-loader?limit=8192'
]
},
]
},
optimization: {
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true,
uglifyOptions: {
compress: false,
ecma: 6,
mangle: false
},
sourceMap: true
})
],
splitChunks: {
cacheGroups: {
commons: {
test: /node_modules/,
name: 'vendor',
chunks: 'all'
}
}
}
},
plugins: [ // Array of plugins to apply to build chunk
new HtmlWebpackPlugin({
template: "./src/main/frontend/index.html",
inject: 'body'
}),
new ExtractTextPlugin('/distTemp/style/style.css'),
ExtractNormalCSS,
extractCSS
],
devServer: { // configuration for webpack-dev-server
contentBase: '.src/main/frontend/assets', //source of static assets
port: 7700, // port to run dev-server
}
};
Upon building, I am getting the error mentioned below.
ERROR in ./src/main/frontend/sass/main.scss (./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/main/frontend/sass/main.scss)
Module build failed (from ./node_modules/sass-loader/lib/loader.js):
var path = require("path");
^
Invalid CSS after "v": expected 1 selector or at-rule, was "var path = require("
in ###/node_modules/bourbon/index.js (line 1, column 1)
Error:
var path = require("path");
^
Invalid CSS after "v": expected 1 selector or at-rule, was "var path = require("
in ###/node_modules/bourbon/index.js (line 1, column 1)
at options.error (###/node_modules/node-sass/lib/index.js:291:26)
# ./src/main/frontend/sass/main.scss 2:14-134
# multi ./src/main/frontend/app/app.js ./src/main/frontend/sass/main.scss
I am using sass-loader and node-sass for the .scss files.
The main.scss file contains imports for the rest of the style files.
Could someone assist me in resolving this error please?

Unit testing in React + Mocha + Enzyme i + Webpack - how to ignore imported files?

I'm trying to Unit Test React on the Front End in Mocha & Enzyme. The testing stops when Mocha gets into the app file and parses over import statements:
import 'script!jquery';
import 'script!what-input';
import 'script!foundation-sites';
I was able to ignore .css and .scss files in the package.json test command:
"test": "mocha --compilers js:babel-register --require ./test/client/test_helper.js --require ignore-styles --recursive",
"test/client:watch": "npm test -- --watch"
I'm not clear on how to ignore these import files, and if I'm going about this the wrong way. (I found the solution for ignore-styles here in Stack Overflow but not something like this.
The error I get:
module.js:341
throw err;
^
Error: Cannot find module 'script!jquery'
New to Unit testing, any help appreciated.
update:
// babelrc
{
"presets": ["es2015", "stage-0", "react"],
"plugins": ["transform-runtime"],
"env": {
"development": {
"presets": ["react-hmre"]
},
"production": {
"presets": ["react-hmre"]
}
}
}
// webpack.config.js
var path = require('path');
var webpack = require('webpack');
var autoprefixer = require('autoprefixer');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: __dirname + '/client/index.html',
filename: 'index.html',
inject: 'body'
});
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: [
'webpack-hot-middleware/client',
'./client/index.js'
],
output: {
path: __dirname + '/dist',
filename: 'bundle.js'
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new ExtractTextPlugin("bundle.css"),
HtmlWebpackPluginConfig
],
module: {
loaders: [
{
test: /\.js$/,
loaders: [ 'babel' ],
exclude: /node_modules/,
include: path.join(__dirname, 'client')
},
// fonts and svg
{ test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" },
{ test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream" },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file" },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml" },
{
// images
test: /\.(ico|jpe?g|png|gif)$/,
loader: "file"
},
{
// for some modules like foundation
test: /\.scss$/,
exclude: [/node_modules/], // sassLoader will include node_modules explicitly
loader: ExtractTextPlugin.extract("style", "css!postcss!sass?outputStyle=expanded")
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract("style", "css!postcss")
}
]
},
postcss: function(webpack) {
return [
autoprefixer({browsers: ['last 2 versions', 'ie >= 9', 'and_chr >= 2.3']})
];
},
sassLoader: {
includePaths: [path.resolve(__dirname, "node_modules")]
}
};
script/run.sh points to a test-helper file:
/* jshint undef: false, unused: false */
process.env.NODE_ENV = 'test';
// The following allows you to require files independent of
// the location of your test file.
// Example:
// var User = require(__server + '/models/user.js')
//
global.__server = __dirname + '/../server';
global.__client = __dirname + '/../client';
//
// Assertions
//
var chai = require('chai');
// Option 1: Make the `expect` function available in every test file
global.expect = chai.expect;
// Option 2: Make everything should-able
// global.should = chai.should()
//
// Helper Functions
//
// This is the object you can attach any helper functions used across
// several test files.
global.TestHelper = {};
var db = require('../server/db.js');
TestHelper.setup = function(){
return db.deleteEverything();
};
//
// Mock apps for API testing
//
var express = require('express');
TestHelper.createApp = function (loader) {
var app = express();
app.use(require('body-parser').json());
app.testReady = function () {
// Log all errors
app.use(function (err, req, res, next) {
console.error('==Error==');
console.error(' ' + err.stack);
next(err);
});
};
return app;
};
//
// Mocha "helpers" to support coroutines tests
//
var Bluebird = require('bluebird');
global.before_ = function (f) { before ( Bluebird.coroutine(f) ); };
global.beforeEach_ = function (f) { beforeEach ( Bluebird.coroutine(f) ); };
global.it_ = function (description, f) { it ( description, Bluebird.coroutine(f) ); };
global.xit_ = function (description, f) { xit ( description, f ); };
global.it_.only = function (description, f) { it.only( description, Bluebird.coroutine(f) ); };
I'm not entirely sure how the helper file is well, helping, since the back end team member put it together for his unit tests - but it looks like it could be promising.
Thanks for your time.

Module not found: Error: Cannot resolve 'file' or 'directory'

Can you guys please help me fixing this issue.
I have two .jsx files one imported under another one.
Lets say,
A.jsx(Inside A.jsx I have imported the B.jsx)
B.jsx
When both the files are written under same file in that case unit test cases working fine. The moment I am separating it out, still the component is working fine but the unit test cases are not running. Webpack karma throwing an error saying
ERROR in ./src/components/thpfooter/index.jsx Module not found: Error: Cannot resolve 'file' or 'directory' ./ThpFooterList in /Users/zi02/projects/creps_ui_components_library/src/components/thpfooter # ./src/components/thpfooter/index.jsx 9:1725-1751
karma.conf.js
/*eslint-disable*/
var webpack = require('karma-webpack');
var argv = require('yargs').argv;
var componentName = "**";
if (typeof argv.comp !== 'undefined' && argv.comp !== null && argv.comp !== "" && argv.comp !== true) {
componentName = argv.comp;
}
var testFiles = 'src/components/'+componentName+'/test/*.js';
var mockFiles = 'src/components/'+componentName+'/test/mock/*.json';
module.exports = function (config) {
config.set({
frameworks: ['jasmine'],
files: [
'./node_modules/phantomjs-polyfill/bind-polyfill.js',
testFiles,
mockFiles
],
plugins: [webpack,
'karma-jasmine',
'karma-phantomjs-launcher',
'karma-coverage',
'karma-spec-reporter',
'karma-json-fixtures-preprocessor',
'karma-junit-reporter'],
browsers: ['PhantomJS'],
preprocessors: {
'src/components/**/test/*.js': ['webpack'],
'src/components/**/*.jsx': ['webpack'],
'src/components/**/test/mock/*.json': ['json_fixtures']
},
jsonFixturesPreprocessor: {
// strip this from the file path \ fixture name
stripPrefix: 'src/components/',
// strip this to the file path \ fixture name
prependPrefix: '',
// change the global fixtures variable name
variableName: '__mocks__',
// camelize fixture filenames
// (e.g 'fixtures/aa-bb_cc.json' becames __fixtures__['fixtures/aaBbCc'])
camelizeFilenames: true,
// transform the filename
transformPath: function (path) {
return path + '.js';
}
},
reporters: ['spec', 'coverage','junit'],
coverageReporter: {
dir: 'build/reports/coverage',
reporters: [
{ type: 'html', subdir: 'report-html' },
{ type: 'lcov', subdir: 'report-lcov' }
]
},
junitReporter: {
outputDir: 'build/reports/coverage/junit/'+componentName,
suite: ''
},
webpack: {
module: {
loaders: [{
test: /\.(js|jsx)$/, exclude: /node_modules/,
loader: 'babel-loader'
}],
postLoaders: [{
test: /\.(js|jsx)$/, exclude: /(node_modules|test)/,
loader: 'istanbul-instrumenter'
}]
}
},
webpackMiddleware: { noInfo: true }
});
};
footer.jsx
import React from 'react';
import ThpFooterList from './ThpFooterList';
class ThpFooter extends React.Component {
//footer code here
}
ThpFooterList.jsx
import React from 'react';
class ThpFooterList extends React.Component {
//footer list code here
}
See above component is working but I am not able to execute the unit test case. When you keep both of them in one file means footer and footerlist.jsx then component as well as the unit test cases are executing.
unit test case file
/* eslint-env jasmine */
import React from 'react';
import TestUtils from 'react/lib/ReactTestUtils';
import ThpFooter from '../index.jsx';
describe('ThpFooter', () => {
let component;
let content;
let shallowRenderer;
let componentShallow;
beforeAll(() => {
content = window.__mocks__['thpfooter/test/mock/content'];
component = TestUtils.renderIntoDocument(<ThpFooter data={content}/>);
shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(<ThpFooter data={content}/>);
componentShallow = shallowRenderer.getRenderOutput();
});
describe('into DOM', () => {
it('Should be rendered into DOM', () => {
expect(component).toBeTruthy();
});
it('Should have classname as footer-container', () => {
const classname = TestUtils.scryRenderedDOMComponentsWithClass(component, 'footer-container');
expect(classname[0].className).toBe('footer-container');
});
it('Should have className as footer-wrapper', () => {
const classname = TestUtils.scryRenderedDOMComponentsWithClass(component, 'footer-wrapper');
expect(classname[0].className).toBe('footer-wrapper');
});
});
describe('into shallow renderer', () => {
it('Should be rendered as shallow renderer', () => {
expect(componentShallow).toBeTruthy();
});
it('Should have classname as footer-container', () => {
expect(componentShallow.props.className).toBe('footer-container');
});
it('Should have className as footer-wrapper', () => {
expect(componentShallow.props.children.props.children[0].props.className).toBe('footer-wrapper');
});
});
});
I experienced the same error on one of the development machines. Although gulp and webpack-stream was used in my case, I think you may reference my method to try solving it.
On my mac, everything is fine but when I pushed the code to the ubuntu development platform, this problem was observed. After some googling I cannot solve it but then I tried to make the file path to be shorter and then suddenly it works on the ubuntu development platform too! You may try to shorten the file name or place it in a shorter path and test to see if it works.
Watch for case sensitivity. Mac file system is not case-sensitive, windows/linux is.

Ember Acceptance Test Failing in PhantomJS but Passing in Chrome

I'm trying to write an acceptance test for my Ember app and I seem to be having some trouble when it comes to PhantomJS and the Ember test server.
I'm running the following versions:
Ember : v1.13.6
Ember Data : v1.13.7
PhantomJS is failing with the following error:
Died on test #1 at http://localhost:7357/assets/test-support.js:2934
at http://localhost:7357/assets/test-support.js:6640
at http://localhost:7357/assets/test-loader.js:31
at http://localhost:7357/assets/test-loader.js:21
at http://localhost:7357/assets/test-loader.js:40
at http://localhost:7357/assets/test-support.js:6647: Can't find variable: DS
Is this a known issue?
The test is running fine within the chrome runner.
Here is my ember-cli-build.js (Brocfile):
/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
module.exports = function(defaults) {
// Build Options
var options = {
// Build for development (ember s)
development: {
sassOptions: {
includePaths: ['bower_components/materialize/sass']
}
},
// Build for deployments
dev_deploy: {
sassOptions: {
includePaths: ['bower_components/materialize/sass']
},
fingerprint: {
enabled: true,
prepend: 'redacted',
extensions: ['js', 'css', 'png', 'jpg', 'gif', 'woff', 'ttf']
}
},
// Build for deployments
staging_deploy: {
sassOptions: {
includePaths: ['bower_components/materialize/sass']
},
fingerprint: {
enabled: true,
prepend: 'redacted',
extensions: ['js', 'css', 'png', 'jpg', 'gif', 'woff', 'ttf']
}
},
prod_deploy: {
sassOptions: {
includePaths: ['bower_components/materialize/sass']
},
fingerprint: {
enabled: true,
prepend: 'redacted',
extensions: ['js', 'css', 'png', 'jpg', 'gif', 'woff', 'ttf']
}
}
};
var env = process.env.EMBER_ENV || 'development';
var app = new EmberApp(defaults, options[env]);
// IMPORTED LIBRARIES
app.import('vendor/js/ember-uploader.named-amd.js', {
exports: {
'ember-uploader': [ 'default' ]
}
});
app.import('vendor/js/faye-browser.js');
app.import('vendor/js/Util.js');
app.import('vendor/js/CanvasVirtualJoyStick.js');
app.import('vendor/js/CanvasZoomController.js');
app.import('vendor/js/chosen.jquery.js');
app.import('vendor/css/chosen.css');
return app.toTree();
};
Here is my test:
import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from 'teal-turtle/tests/helpers/start-app';
var application;
module('Acceptance | platforms', {
beforeEach: function() {
application = startApp();
},
afterEach: function() {
Ember.run(application, 'destroy');
}
});
test('visiting /platforms', function(assert) {
authenticateSession();
visit('/platforms');
andThen(function() {
assert.equal(currentURL(), '/platforms');
});
});
Thanks!
I noticed you were using .bind in the route file (platform) and .bind isn't very phantomJS friendly :( so I did the following...
Added the es5 shim and broccoli funnel to your package.json
"broccoli-funnel": "^0.2.3",
"es5-shim": "^4.0.5"
Next I opened the ember-cli-build.js (prev known as the Brocfile)
var funnel = require('broccoli-funnel');
var es5Shim = funnel('node_modules/es5-shim', {
files: ['es5-shim.js'],
destDir: '/assets'
});
return app.toTree([es5Shim]);
And finally I added the es5 shim to your tests/index.html above vendor.js
<script src="assets/es5-shim.js"></script>
Below is a full commit on github showing all the files changed (note: Brocfile in this commit example because I'm using an older ember-cli version)
https://github.com/toranb/ember-cli-simple-store/commit/4f46a392b3be0ec93864342ba2edddbd3430e293