I am trying to implement a form in ionic 2 and am having a problem with the skeleton code I have written. When running ionic serve it throws the error unexpected token on line 8 of the following code in my form.js file:
import {FormBuilder, Validators, formDirectives, ControlGroup} from 'angular2/common';
#Page({
templateUrl: 'build/pages/photo/photo.html',
})
export class PhotoPage {
constructor(form:FormBuilder){
this.submitMediaItem = {};
this.submitted = false;
this.name = new Control('', Validators.required);
}
Hi I had the same error previously. You can try this solution:
Check your version of ionic 2 using the command ionic -v. Mostly likely you are using the newer version of ionic 2 (mine is 2.0.0-beta.24).
For the earlier beta version, it uses typescript so form:FormBuilder is valid typescript but not valid javascript. The newer version has moved on with babel JS so you will need to do as such:
import {FormBuilder, Validators, formDirectives, ControlGroup} from 'angular2/common';
#Page({
templateUrl: 'build/pages/photo/photo.html'
})
export class PhotoPage {
static get parameters(){
return [FormBuilder];
}
constructor(form){
this.form = form; //or how ever you would like to use it
this.submitMediaItem = {};
this.submitted = false;
this.name = new Control('', Validators.required);
}
}
To return more than 1 parameters, you can do it as such:
return [[FormBuilder],[navController]];
constructor(form, nav){...}
There's a discussion thread regarding this error also: https://forum.ionicframework.com/t/cannot-resolve-all-parameters-error/44969/7
Hope this helps!
Related
I have a global property/variable with my app urls:
Vue.prototype.$apiUrls = {
root: 'http://localhost:8080/',
api: 'api/v1/'
// etc.
}
I use it inside my components as axios request:
axios.get(`${this.$apiUrls.root}${this.$apiUrls.api}/users/`)
Now I want to test my component's code, I've mocked axios already, but still I receive an error:
TypeError: Cannot read property '$apiUrls' of undefined
I've tried to define/mock this property inside each test and/or in JEST's setup file, like e.g.
global.$apiUrls = {...}
// or
Vue.prototype.$apiUrls = {...}
// or
Object.defineProperties(Vue.prototype, {$apiUrls: {...}})
I've also tried mocking it to window or this (yeah, thats silly), but with no success - I still receive that error - please help.
There is two ways to achieve this. One is using the Config option, as mentioned by #Aldarund. You can read about it here.
If you are using Jest, I recommend doing this in the jest.init.js file:
import { config } from '#vue/test-utils'
config.mocks['$apiUrls'] = {
'some/endpoint'
}
Then add this to the jest section of your package.json:
"setupFiles": [
"<rootDir>/jest.init.js"
]
Now it is globally mocked. If you want to do this on a per test basis, you can use the mocks mounting option:
const wrapper = shallowMount(Foo, {
mocks: {
$apiUrls: 'some/endpoint'
}
})
Hopefully this helps!
If you are interested I am compiling a collection of simple guides on how to test Vue components here. It's under development, but feel free to ask make an issue if you need help with other related things to testing Vue components.
I don't think the answers above work anymore (in 2020).
Here's what worked for me:
For vue-test-utils 1.x.x (Vue 2)
Create a new file, name it eg. jest.init.js
Give it the following content:
import { config } from "#vue/test-utils";
config.mocks["yourGlobalProperty"] = label => label; //you can replace it with your own mock
Add this to your jest.config.js (actually write "rootDir", don't replace anything with a real path)
module.exports = {
setupFiles: ["<rootDir>/jest.init.js"]
}
These files will be only ran before jest runs unit tests.
Note that I'm importing {config}, not the default export. I don't know why the default didn't work for me. Even the documentation for vue test utils doesn't import the default export anymore
Also make sure you're not trying to import from the old vue-test-utils package. (The new one is #vue/test-utils)
For #vue/test-utils 2.x.x (vue-test-utils-next) (Vue 3)
Follow steps like for 1.x.x above, but in step two, do this instead:
import { config } from "#vue/test-utils"; //2.0.0-beta.5
config.global.mocks = {
yourGlobalProperty: label => label
};
You can do it with vue-test-utils beta 15 and later.
Here docs
And some example would be:
import VueTestUtils from '#vue/test-utils'
VueTestUtils.config.mocks['$apiUrls'] = {
...
}
export class ProjectDetail {
page: string;
}
the page info contained in json, like this:
{
"data":[
{
page: "PageInfoPage"
},
{
page: "PageInfoPage1"
}
]
}
I parse info from this json,then saved in Array.
when execute this.nav.push(pd.page),throw exception as title described.I don't know how to convert 'string' to 'component'.
============================================================
I use the method like Angular 2 - Resolve Component Factory with a string described. This is my code:
itemClick(pd: ProjectDetail) {
var factories = Array.from(this.resolver['_factories'].keys());
var factoryClass = <Type<any>>factories.find((x: any) => x.name === pd.page);
const factory = this.resolver.resolveComponentFactory(factoryClass);
const compRef = this.vcRef.createComponent(factory);
if (this.componentRef) {
this.componentRef.destroy();
}
this.componentRef = compRef;
this.nav.push(compRef, {
item: pd,
pid: this.project.pid
});
}
it still does not work.Thank you for your answer.
At last,I solved it with a stupid method.As I create a map like this:
componentRegistry = {
'ProjectInfoPage': ProjectInfoPage
};
And then push like this:
this.nav.push(this.componentRegistry[pd.page], {
item: pd,
pid: this.project.pid
});
Normally, you have to import the actual component class for the page that you want to navigate to and then push that class onto the stack. By default, there is no way built into ionic2 to navigate via string references. I had the same problem today where I wanted to be able to navigate using strings rather than pushing the component class on the stack.
Check out the following link from the ionic forums on how to accomplish this. Look at the last two responses to the thread, which include how to solve this problem from beta stages and then an updated answer for how to do so with ionic 2.2.0. Although I'm pretty sure the same solution will work for all versions of ionic 2 since final release.
https://forum.ionicframework.com/t/ionic2-navigation-circular-depencies/41123/5
I' using the latest release version of webstorm (9.03) and most of my JavaScript files show up as invalid. I'm showing the code below.
'use strict';
function SpeakerDetailsController (speaker, CONFIG, $sce, $scope) {
this.speaker = speaker;
this.showSessions = CONFIG.showSessions === 'True';
$scope.someSafeContent = $sce.trustAsHtml("<i>Hello</i> <b>World!</b>");
}
SpeakerDetailsController.$inject = ['speaker', 'CONFIG', '$sce', '$scope'];
export default SpeakerDetailsController;
Please make sure to set JavaScript Language Version to 'ECMAScript 6' (or 'JSX Harmony') in Settings/Languages&Frameworks/JavaScript to get ES6 syntax correctly recognized.
I'm trying to utilize the build-test-data plugin in my Grails (v2.4.3) app to assist with test data creation for unit testing, but while running my unit tests the plugin cannot find TestDataConfig.groovy to load my specified values (for unique constraint tests, etc).
I've installed the plugin via including it in BuildConfig.groovy:
plugins {
...
test ":build-test-data:2.2.0"
...
}
I've ran the following command to create the TestDataConfig.groovy template, which places the file at \grails-app\conf\:
grails install-build-test-data-config-template
I've followed the general instructions on the plugin wiki to come up with a properly formatted file:
testDataConfig {
sampleData {
'<path>.User' {
def a = 1
username = { -> "username${a++}" }
}
}
}
(Where path is the fully-qualified class name.)
In my tests, I am using the following general format:
import grails.buildtestdata.TestDataConfigurationHolder
import grails.buildtestdata.mixin.Build
import grails.test.mixin.TestFor
import spock.lang.Specification
import spock.lang.Unroll
#TestFor(User)
#Build(User)
class UserSpec extends Specification {
def setup() {
mockForConstraintsTests(User)
TestDataConfigurationHolder.reset()
user = User.buildWithoutSave()
}
#Unroll
void "test #field must be unique"() {
given: 'a User exists'
user.save(flush: true)
when: 'another User is created with a non-unique field value'
def nonUniqueUser = User.buildWithoutSave()
nonUniqueUser."$field" = user."$field"
then: 'validation fails and the field has a unique constraint error'
!nonUniqueUser.validate()
nonUniqueUser.errors.errorCount == 1
nonUniqueUser.errors.getFieldError("$field").code == 'unique'
where:
field << ['username', '<some other field>']
}
}
But, when the test is run (using IntelliJ IDEA) TestDataConfig.groovy cannot be found via the following method in the plugin:
static Class getDefaultTestDataConfigClass() {
GroovyClassLoader classLoader = new GroovyClassLoader(TestDataConfigurationHolder.classLoader)
String testDataConfig = Holders.config?.grails?.buildtestdata?.testDataConfig ?: 'TestDataConfig'
try {
return classLoader.loadClass(testDataConfig)
} catch (ClassNotFoundException ignored) {
log.warn "${testDataConfig}.groovy not found, build-test-data plugin proceeding without config file"
return null
}
}
So the test continues on without a config file and I do not get uniquely generated data sets.
I've even tried explicitly including the file in Config.groovy:
grails.buildtestdata.testDataConfig = "TestDataConfig"
But, the same method in the plugin shows that Holders.config? is null.
I've looked at a few solutions to a similar problem here on StackOverflow with nothing working in my case; I cannot figure out how to get my app to detect the presence of the TestDataConfig.groovy file.
Any ideas? Thanks so much!
I just started practice tests on angular-seed app based on Jasmine. When using the first test example found on pivotal.github.io/jasmine/ it fails on my app.
Test example code:
describe("A suite", function() {
it("contains spec with an expectation", function() {
expect(true).toBe(true);
});
});
but passes on tryjasmine.com
I did a test for content and views/partials, they pass. but the one on the jasmine site fails. Am I missing something or is there some config I need to setup?
Karma.conf.js file:
basePath = '../';
files = [
JASMINE,
JASMINE_ADAPTER,
'app/lib/angular/angular.js',
'app/lib/angular/angular-*.js',
'test/lib/angular/angular-mocks.js',
'app/js/**/*.js',
'test/unit/**/*.js'
];
autoWatch = true;
browsers = ['Chrome'];
junitReporter = {
outputFile: 'test_out/unit.xml',
suite: 'unit'
};
Karma-e2e.conf.js file:
basePath = '../';
files = [
ANGULAR_SCENARIO,
ANGULAR_SCENARIO_ADAPTER,
'test/e2e/**/*.js'
];
autoWatch = false;
browsers = ['Chrome'];
singleRun = true;
proxies = {
'/': 'http://localhost:8000/'
};
junitReporter = {
outputFile: 'test_out/e2e.xml',
suite: 'e2e'
};
According to http://pivotal.github.io/jasmine/#section-The_Runner_and_Reporter on the Runner and Reporter section of the doc there is:
document.querySelector('.version').innerHTML = jasmineEnv.versionString();
browser console throws an error
Uncaught TypeError: Cannot set property 'innerHTML' of null
after looking around I found other examples dont have that line. I used the example in tuts+ http://net.tutsplus.com/tutorials/javascript-ajax/testing-your-javascript-with-jasmine/
On that tutorial there is SpecRunner.html it has that block of code without document.querySelector('.version').innerHTML = jasmineEnv.versionString();
and everything works as expected.
You're using old karma's configuration style. I see two options
1) you have quite old karma version,
2) you are trying to run new karma on the old configuration style.
You should try to upgrade karma to the newest version and migrate your configuration to the new style, see: http://karma-runner.github.io/0.10/config/configuration-file.html
You can comment:
document.querySelector('.version').innerHTML = jasmineEnv.versionString();
Or you can add in your body:
<div class='version'></div>