Ember Acceptance Test Failing in PhantomJS but Passing in Chrome - ember.js

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

Related

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

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: [],
}),
],
},
},
});

Aurelia unit testing access component's viewModel

I am unit testing one of my components in an Aurelia project. I'd like to access my component's viewModel in my unit test but haven't had any luck so far.
I followed the example available at https://aurelia.io/docs/testing/components#manually-handling-lifecycle but I keep getting component.viewModel is undefined.
Here is the unit test:
describe.only('some basic tests', function() {
let component, user;
before(() => {
user = new User({ id: 100, first_name: "Bob", last_name: "Schmoe", email: 'joe#schmoe.com'});
user.save();
});
beforeEach( () => {
component = StageComponent
.withResources('modules/users/user')
.inView('<user></user>')
.boundTo( user );
});
it('check for ', () => {
return component.create(bootstrap)
.then(() => {
expect(2).to.equal(2);
return component.viewModel.activate({user: user});
});
});
it('can manually handle lifecycle', () => {
return component.manuallyHandleLifecycle().create(bootstrap)
.then(() => component.bind({user: user}))
.then(() => component.attached())
.then(() => component.unbind() )
.then(() => {
expect(component.viewModel.name).toBe(null);
return Promise.resolve(true);
});
});
afterEach( () => {
component.dispose();
});
});
Here is the error I get:
1) my aurelia tests
can manually handle lifecycle:
TypeError: Cannot read property 'name' of undefined
Here is the the line that defines the viewModel on the component object but only if aurelia.root.controllers.length is set. I am not sure how to set controllers in my aurelia code or if I need to do so at all.
I guess my question is:
How do I get access to a component's viewModel in my unit tests?
Edit #2:
I'd also like to point out that your own answer is essentially the same solution as the one I first proposed in the comments. It is the equivalent of directly instantiating your view model and not verifying whether the component is actually working.
Edit:
I tried this locally with a karma+webpack+mocha setup (as webpack is the popular choice nowadays) and there were a few caveats with getting this to work well. I'm not sure what the rest of your setup is, so I cannot tell you precisely where the error was (I could probably point this out if you told me more about your setup).
In any case, here's a working setup with karma+webpack+mocha that properly verifies the binding and rendering:
https://github.com/fkleuver/aurelia-karma-webpack-testing
The test code:
import './setup';
import { Greeter } from './../src/greeter';
import { bootstrap } from 'aurelia-bootstrapper';
import { StageComponent, ComponentTester } from 'aurelia-testing';
import { PLATFORM } from 'aurelia-framework';
import { assert } from 'chai';
describe('Greeter', () => {
let el: HTMLElement;
let tester: ComponentTester;
let sut: Greeter;
beforeEach(async () => {
tester = StageComponent
.withResources(PLATFORM.moduleName('greeter'))
.inView(`<greeter name.bind="name"></greeter>`)
.manuallyHandleLifecycle();
await tester.create(bootstrap);
el = <HTMLElement>tester.element;
sut = tester.viewModel;
});
it('binds correctly', async () => {
await tester.bind({ name: 'Bob' });
assert.equal(sut.name, 'Bob');
});
it('renders correctly', async () => {
await tester.bind({ name: 'Bob' });
await tester.attached();
assert.equal(el.innerText.trim(), 'Hello, Bob!');
});
});
greeter.html
<template>
Hello, ${name}!
</template>
greeter.ts
import { bindable } from 'aurelia-framework';
export class Greeter {
#bindable()
public name: string;
}
setup.ts
import 'aurelia-polyfills';
import 'aurelia-loader-webpack';
import { initialize } from 'aurelia-pal-browser';
initialize();
karma.conf.js
const { AureliaPlugin } = require('aurelia-webpack-plugin');
const { resolve } = require('path');
module.exports = function configure(config) {
const options = {
frameworks: ['source-map-support', 'mocha'],
files: ['test/**/*.ts'],
preprocessors: { ['test/**/*.ts']: ['webpack', 'sourcemap'] },
webpack: {
mode: 'development',
entry: { setup: './test/setup.ts' },
resolve: {
extensions: ['.ts', '.js'],
modules: [
resolve(__dirname, 'src'),
resolve(__dirname, 'node_modules')
]
},
devtool: 'inline-source-map',
module: {
rules: [{
test: /\.html$/i,
loader: 'html-loader'
}, {
test: /\.ts$/i,
loader: 'ts-loader',
exclude: /node_modules/
}]
},
plugins: [new AureliaPlugin()]
},
singleRun: false,
colors: true,
logLevel: config.browsers && config.browsers[0] === 'ChromeDebugging' ? config.LOG_DEBUG : config.LOG_INFO, // for troubleshooting mode
mime: { 'text/x-typescript': ['ts'] },
webpackMiddleware: { stats: 'errors-only' },
reporters: ['mocha'],
browsers: config.browsers || ['ChromeHeadless'],
customLaunchers: {
ChromeDebugging: {
base: 'Chrome',
flags: [ '--remote-debugging-port=9333' ]
}
}
};
config.set(options);
};
tsconfig.json
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"importHelpers": true,
"lib": ["es2018", "dom"],
"module": "esnext",
"moduleResolution": "node",
"sourceMap": true,
"target": "es2018"
},
"include": ["src"]
}
package.json
{
"scripts": {
"test": "karma start --browsers=ChromeHeadless"
},
"dependencies": {
"aurelia-bootstrapper": "^2.3.0",
"aurelia-loader-webpack": "^2.2.1"
},
"devDependencies": {
"#types/chai": "^4.1.6",
"#types/mocha": "^5.2.5",
"#types/node": "^10.12.0",
"aurelia-testing": "^1.0.0",
"aurelia-webpack-plugin": "^3.0.0",
"chai": "^4.2.0",
"html-loader": "^0.5.5",
"karma": "^3.1.1",
"karma-chrome-launcher": "^2.2.0",
"karma-mocha": "^1.3.0",
"karma-mocha-reporter": "^2.2.5",
"karma-source-map-support": "^1.3.0",
"karma-sourcemap-loader": "^0.3.7",
"karma-webpack": "^3.0.5",
"mocha": "^5.2.0",
"path": "^0.12.7",
"ts-loader": "^5.2.2",
"typescript": "^3.1.3",
"webpack": "^4.23.1",
"webpack-dev-server": "^3.1.10"
}
}
Original answer
If you're manually doing the lifecycle, you need to pass in a ViewModel yourself that it can bind to :)
I don't remember exactly what's strictly speaking needed so I'm quite sure there's some redundancy (e.g. one of the two bindingContexts passed in shouldn't be necessary). But this is the general idea:
const view = "<div>${msg}</div>";
const bindingContext = { msg: "foo" };
StageComponent
.withResources(resources/*optional*/)
.inView(view)
.boundTo(bindingContext)
.manuallyHandleLifecycle()
.create(bootstrap)
.then(component => {
component.bind(bindingContext);
}
.then(component => {
component.attached();
}
.then(component => {
expect(component.host.textContent).toEqual("foo");
}
.then(component => {
bindingContext.msg = "bar";
}
.then(component => {
expect(component.host.textContent).toEqual("bar");
};
Needless to say, since you create the view model yourself (the variable bindingContext in this example), you can simply access the variable you declared.
In order to get it to work, I had to use Container:
import { UserCard } from '../../src/modules/users/user-card';
import { Container } from 'aurelia-dependency-injection';
describe.only('some basic tests', function() {
let component, user;
before(() => {
user = new User({ id: 100, first_name: "Bob", last_name: "Schmoe", email: 'joe#schmoe.com'});
user.save();
});
beforeEach(() => {
container = new Container();
userCard = container.get( UserCard );
component = StageComponent
.withResources('modules/users/user-card')
.inView('<user-card></user-card>')
.boundTo( user );
});
it('check for ', () => {
return component.create(bootstrap)
.then(() => {
expect(2).to.equal(2);
return userCard.activate({user: user});
});
});
});

How do I unit test a quasar app using Jest?

I have an quasar application that was generated with the quasar-cli.
How do I integrate a unit test into a test runner like Jest for an application like this?
I've added a this to my Jest configuration
"moduleNameMapper": {
"quasar": "<rootDir>/node_modules/quasar-framework"
}
Unfortunately, Jest reports back
Cannot find module 'quasar' from 'index.vue'
Here is the a snippet of the Vue file
<template>
<div style="padding-top: 20px" v-if="refund.type != null ">
<q-btn :label="'Issue ' + ( currency(refund.amount)) + ' Refund'" :disable="refund.amount <= 0" #click="issueRefund()" color="green" class="full-width" :loading="noteLoading" />
</div>
</template>
<script>
import { Notify } from "quasar"; // here is where I am using Quasar
issueRefund() {
this.noteLoading = true;
this.$axios
.post(`${BASE_URL}/issue_refund/?secret=${this.secret}`, {
refund: this.refund,
agent_email: this.userEmail,
order_id: this.selectedOrder.id,
agent_name: this.$route.query.user_name,
order_number: this.selectedOrder.order_number,
ticket_id: this.ticketId
})
.then(res => {
this.noteLoading = false;
if ((res.data.res === "success")) {
Notify.create({
position: "bottom",
type: "positive",
message: "Refund Issued."
});
this.selectedOrder = res.data.order;
this.resetRefundObj();
this.$refs.refundDiag.hide();
} else {
Notify.create({
position: "bottom",
type: "negative",
message: res.data.error
});
}
});
},
</script>
Integrating Jest with Quasar is quite straight-forward. You'll need two packages, babel-jest and jest.
yarn add jest babel-jest -D
After adding those two dependencies, create a jest.config.js file at the root of your project--here's where all the jest configuration goes.
Here's how the jest.config.js file should look like;
module.exports = {
globals: {
__DEV__: true,
},
verbose: false, // false since we want to see console.logs inside tests
bail: false,
testURL: 'http://localhost/',
testEnvironment: 'jsdom',
testRegex: './__unit__/.*.js$',
rootDir: '.',
testPathIgnorePatterns: [
'<rootDir>/components/coverage/',
'<rootDir>/test/cypress/',
'<rootDir>/test/coverage/',
'<rootDir>/dist/',
'<rootDir>/node_modules/',
],
moduleFileExtensions: ['js', 'json', 'vue'],
moduleNameMapper: {
'^vue$': 'vue/dist/vue.common.js',
'quasar': 'quasar-framework/dist/umd/quasar.mat.umd.js',
},
resolver: null,
transformIgnorePatterns: [
'node_modules/core-js',
'node_modules/babel-runtime',
'node_modules/vue',
],
transform: {
'^.+\\.js$': '<rootDir>/node_modules/babel-jest',
'.*\\.(vue)$': '<rootDir>/node_modules/vue-jest',
}
}
Then create a folder inside the root of your project called __unit__
Place a file called MyUnitTest.test.js inside the __unit__ folder. Now Jest picks up files from this folder.
The final touch would be to run the tests, simply add this to the package.json
"unit": "yarn run jest --config jest.config.js"
Boom! -- Now you may run yarn run unit or yarn run unit --watch and it should work.
Here's a sample of a Quasar component and Jest test.
import { createLocalVue, shallowMount } from '#vue/test-utils'
import Vuex from 'vuex'
import Quasar, * as All from 'quasar'
import CookieConsent from '#components/common/CookieConsent.vue'
const localVue = createLocalVue()
localVue.use(Vuex)
localVue.use(Quasar, { components: All, directives: All, plugins: All })
describe('CookieConsent.vue', () => {
const wrapper = shallowMount(CookieConsent, {
localVue,
mocks: {
$t: () => {},
},
})
test('CookieConsent.vue mock should exist', () => {
expect(wrapper.exists()).toBe(true)
})
})
Hope you found this useful

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.

Server side proxy for divshot not rendering JSON api in Ember app

I can start my ember/rails server by running ember serve --proxy http://localhost:3000.
I have create a divshot account in order to push this app to a production server but am having trouble passing in the url to my json api.
//divshot.json
{
"name": "project-name",
"root": "./dist",
"routes": {
"/tests": "tests/index.html",
"/tests/**": "tests/index.html",
"/**": "index.html"
},
"proxy": {
"origin": "https://railsapi.herokuapp.com/"
}
}
//environment.js
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'project-name',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
How can I push an app to divshot and use the api I have hosted elsewhere?
ember-cli 1.8.1 - link to project in question
I totally didn’t realise Divshot had this service. Awesome.
Looking at the docs, it seems you need to put the proxy under a named key.
In their example it’s "api":
{
"proxy": {
"api": {
"origin":"https://api.my-app.com",
"headers": {
"Accept": "application/json"
},
"cookies": false,
"timeout": 30
}
}
}
And access it via a special URL of the form /__/proxy/{NAME}/{PATH}:
$.ajax({
url: '/__/proxy/api/users/123',
type: 'POST',
dataType: 'json',
success: function(data) {
// ...
}
})
EDIT:
I left out the actual configuration of your Ember app.
You’ll want to setup API prefix in config/environment.js.
Working locally in development the prefix will be '' and on Divshot it will be /__/proxy/api.
In config/environment.js I like to do this:
module.exports = function(environment) {
// Snip...
ENV.API_PREFIX: process.env.API_PREFIX || '',
};
You can then use this value in app/adapters/application.js like this:
import DS from 'ember-data';
import config from '../config/environment';
export default DS.ActiveModelAdapter.extend({
host: config.apiUrl
});
And specify API_PREFIX on the command line like this:
$ API_PREFIX="/__/proxy/api" ember build
$ divshot push
Hope that helps!