Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Serve assets files from ng test #3628

Merged
merged 2 commits into from
Dec 20, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 23 additions & 0 deletions packages/angular-cli/plugins/karma.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
const path = require('path');
const fs = require('fs');

const getWebpackTestConfig = require('../models/webpack-build-test').getWebpackTestConfig;
const CliConfig = require('../models/config').CliConfig;

Expand All @@ -17,6 +19,27 @@ const init = (config) => {
progress: config.angularCli.progress
}

// add assets
if (appConfig.assets) {
const assets = typeof appConfig.assets === 'string' ? [appConfig.assets] : appConfig.assets;
config.proxies = config.proxies || {};
assets.forEach(asset => {
const fullAssetPath = path.join(config.basePath, appConfig.root, asset);
const isDirectory = fs.lstatSync(fullAssetPath).isDirectory();
const filePattern = isDirectory ? fullAssetPath + '/**' : fullAssetPath;
const proxyPath = isDirectory ? asset + '/' : asset;
config.files.push({
pattern: filePattern,
included: false,
served: true,
watched: true
});
// The `files` entry serves the file from `/base/{appConfig.root}/{asset}`
// so, we need to add a URL rewrite that exposes the asset as `/{asset}` only
config.proxies['/' + proxyPath] = '/base/' + appConfig.root + '/' + proxyPath;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are proxies always needed?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm no karma expert and worked my way through trial and error really, but according to the docs and my tries, when you add a file to the files array, it gets served from /base/src/path-to-file only. The proxy adds another endpoint (like a URL rewrite) from /path-to-file to /base/src/path-to-file.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@filipesilva I added a comment explaining why we need proxies.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes that makes sense to me. I remember a similar situation I ran into another project. Without the proxy, fetch would not work correctly.

});
}

// add webpack config
const webpackConfig = getWebpackTestConfig(config.basePath, environment, appConfig, testConfig);
const webpackMiddlewareConfig = {
Expand Down
63 changes: 60 additions & 3 deletions tests/e2e/tests/test/test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,65 @@
import {ng} from '../../utils/process';
import { writeMultipleFiles } from '../../utils/fs';
import { ng } from '../../utils/process';
import { updateJsonFile } from '../../utils/project';
import { expectToFail } from '../../utils/utils';
import { stripIndent } from 'common-tags';


export default function() {
// make sure both --watch=false and --single-run work
export default function () {
// Each test function returns PromiseLike<Something_Different>,
// which would throw normally
// but resolve() normalizes this to <any> from the start
return Promise.resolve()
.then(() => testWatchFalseAndSingleRun())
.then(() => testAssetsAreServed());
}

// Make sure both --watch=false and --single-run work
function testWatchFalseAndSingleRun() {
return ng('test', '--single-run')
.then(() => ng('test', '--watch=false'));
}

// Make sure asset files are served
function testAssetsAreServed() {
return Promise.resolve()
.then(() => writeMultipleFiles({
'src/assets/file.txt': 'assets-folder-content',
'src/file.txt': 'file-content',
// Not using `async()` in tests as it seemed to swallow `fetch()` errors
'src/app/app.component.spec.ts': stripIndent`
describe('Test Runner', () => {
const fetch = global['fetch'];
it('should serve files in assets folder', (done) => {
fetch('/assets/file.txt')
.then(response => response.text())
.then(fileText => {
expect(fileText).toMatch('assets-folder-content');
done();
});
});
it('should serve files explicitly added to assets array', (done) => {
fetch('/file.txt')
.then(response => response.text())
.then(fileText => {
expect(fileText).toMatch('file-content');
done();
});
});
});
`
}))
// Test failure condition (no assets in angular-cli.json)
.then(() => updateJsonFile('angular-cli.json', configJson => {
const app = configJson['apps'][0];
app['assets'] = [];
}))
.then(() => expectToFail(() => ng('test', '--single-run'),
'Should fail because the assets to serve were not in the angular-cli config'))
// Test passing condition (assets are included)
.then(() => updateJsonFile('angular-cli.json', configJson => {
const app = configJson['apps'][0];
app['assets'] = ['assets', 'file.txt'];
}))
.then(() => ng('test', '--single-run'));
}
9 changes: 6 additions & 3 deletions tests/e2e/utils/utils.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@

export function expectToFail(fn: () => Promise<any>): Promise<void> {
export function expectToFail(fn: () => Promise<any>, errorMessage?: string): Promise<void> {
return fn()
.then(() => {
throw new Error(`Function ${fn.source} was expected to fail, but succeeded.`);
}, () => {});
const functionSource = fn.name || (<any>fn).source || fn.toString();
const errorDetails = errorMessage ? `\n\tDetails:\n\t${errorMessage}` : '';
throw new Error(
`Function ${functionSource} was expected to fail, but succeeded.${errorDetails}`);
}, () => { });
}

export function isMobileTest() {
Expand Down