Deeplink no match - ionic2

I’am trying to nav with my url on my app, but I did that:
platform.ready().then(() => {
this.deeplinks.route( {
'/test': AdminPage,
}).subscribe((match) =>{
alert("MARCHEEEEE");
alert(JSON.stringify(match));
}, (noMatch) =>{
alert("CA MARCHE PAS TON DEEPLINK");
alert(JSON.stringify(noMatch));
});
And when I’am doing : http://localhost/#/test it dosent work

Related

Testing a trigger click on a button does not work in Vue using Jest

Testing a trigger click on a button does not work in Vue using Jest.
When I try to find the button in the wrapper the test passes, but when I try a trigger click on the same button so a method will be called it does not work.
Here is the vue file snapshot of the button:
<v-btn #click="viewAppointment(appointment)" class="ma-2" dark small color="orange" id="view-appointment" data-viewAppointmentBtn>
<v-icon left>mdi-eye</v-icon>
<span>View</span>
</v-btn>
Here is the js file that contains the simple method call::
viewAppointment(appointment) {
this.appointment = appointment;
this.viewAppointmentDialog = !this.viewAppointmentDialog;
},
Here is the .spec.js file for the test::
import './setup.js';
import CoachAppointmentsRequests from '../dashboard/coach/appointments/requests/overview/Overview.vue';
import {shallowMount, createLocalVue} from "#vue/test-utils";
import Vuex from "vuex";
const localVue = createLocalVue();
localVue.use(Vuex);
describe("CoachAppointmentsRequests", () => {
let wrapper;
let store;
let actions;
let state;
let getters;
const $route = {
path: 'appointment/requests/:application_id',
params: { application_id: 123 }
}
actions = {
GET_USER_APPOINTMENTS: jest.fn()
};
state = {
user_appointments: [ {id:1, date: 'May 20, 2020'} ],
all_user_appointments: [ {id:1, date: 'May 20, 2020'} ],
};
getters = {
user_appointments: state => state.user_appointments,
all_user_appointments: state => state.all_user_appointments
};
store = new Vuex.Store({
actions,
getters,
state,
});
const getUserAppointments = jest.fn(() => {
return new Promise(resolve => {
process.nextTick(() => {
resolve({
data: [
{ id:1, appointee_id:2}
]
})
})
})
});
beforeEach(() => {
wrapper = shallowMount(CoachAppointmentsRequests, {
propsData: {},
mocks: {
$route,
},
stubs: {},
methods: {
getUserAppointments,
},
store,
localVue,
});
});
it('click on the view appointment button calls the viewAppointment method', () => {
const viewAppointment = jest.fn();
wrapper.setMethods({ viewAppointment })
const viewAppBtn = wrapper.find('#view-appointment');
viewAppBtn.trigger('click');
expect(viewAppointment).toBeCalled();
});
});
Please I will appreciate your assistance with this issue.
The click handler isn't called immediately after trigger(), but rather it's called in the next tick. However, trigger() returns a Promise that resolves when the component is updated, so you could await the result of the call, as shown in the docs example:
it('clicked it', async () => {
// ...
await viewAppBtn.trigger('click')
expect(viewAppointment).toBeCalled()
})
I had a similar problem. I've used shallowMount to mount vue component and click on button wasn't working. The solution was to change shallowMount to mount.

Jest: How to properly test void functions that include promises?

I'm writing an app with React Native. I use Firebase Cloud Messaging for real time communication. I'm currently writing the unit tests for the FCM code using jest. The problem is that I'm struggling to make it work, since it consists of void functions that contain promises. Let me give you the code:
fcm.js:
import { Alert } from "react-native";
import firebase from "react-native-firebase";
export const checkNotificationsPermission = () => {
firebase
.messaging()
.hasPermission()
.then(enabled => {
if (enabled) {
// User has permissions.
} else {
// User doesn't have permission.
Alert.alert(
alertMessages.firebasePrepareForPermissionTitle,
alertMessages.firebasePrepareForPermissionMessage,
[{ text: buttonTexts.ok, onPress: () => requestNotificationsPermission() }]
);
}
});
};
export const requestNotificationsPermission = () => {
firebase
.messaging()
.requestPermission()
.then(() => {
// User has authorised.
})
.catch(() => {
// User has rejected permissions.
Alert.alert(
alertMessages.firebasePrepareForPermissionTitle,
alertMessages.firebasePermissionDeniedMessage,
[{ text: buttonTexts.ok, onPress: () => {} }]
);
});
};
fcm.test.js:
import firebase from "react-native-firebase";
describe("checkNotificationsPermission", () => {
beforeEach(() => {
return checkNotificationsPermission();
});
afterEach(() => {
jest.clearAllMocks();
});
it("should call firebase's hasPermission", async () => {
expect(firebase.messaging().requestPermission).toHaveBeenCalledTimes(1);
});
});
Here is how I mocked firebase (__mocks__/react-native-firebase.js):
const firebase = {
messaging: jest.fn(() => ({
hasPermission: jest.fn(() => new Promise(resolve => resolve(true))),
requestPermission: jest.fn(() => new Promise(resolve => resolve(true)))
}))
};
export default firebase;
The test fails with Expected mock function to have been called one time, but it was called zero times..Since this wouldn't work and I had a similar question about promises which got answered I tried to apply what I learned there which resulted in the following code.
fcm.js:
import { Alert } from "react-native";
import firebase from "react-native-firebase";
export const checkNotificationsPermission = () =>
new Promise((resolve, reject) => {
firebase
.messaging()
.hasPermission()
.then(enabled => {
if (enabled) {
// User has permissions.
resolve(true);
} else {
// User doesn't have permission.
Alert.alert(
alertMessages.firebasePrepareForPermissionTitle,
alertMessages.firebasePrepareForPermissionMessage,
[
{
text: buttonTexts.ok,
onPress: () =>
requestNotificationsPermission()
.then(() => resolve(true))
.catch(() => reject(false))
}
]
);
}
});
});
export const requestNotificationsPermission = () =>
new Promise((resolve, reject) => {
firebase
.messaging()
.requestPermission()
.then(() => {
// User has authorised.
resolve(true);
})
.catch(() => {
// User has rejected permissions.
reject(true);
Alert.alert(
alertMessages.firebasePrepareForPermissionTitle,
alertMessages.firebasePermissionDeniedMessage,
[{ text: buttonTexts.ok, onPress: () => {} }]
);
});
});
fcm.test.js:
import firebase from "react-native-firebase";
import { requestNotifcationsPermission } from "./fcm";
describe("checkNotificationsPermission", () => {
afterEach(() => {
jest.clearAllMocks();
});
it("should call firebase's hasPermission", () => {
expect.assertions(1);
return checkNotificationsPermission().then(() => {
expect(firebase.messaging().requestPermission).toHaveBeenCalledTimes(1);
});
});
});
But for some reason these tests still fail. I empirically tested and ensured the code works. Just the unit tests won't pass.
Edit
I accidentally left out that both fcm.js also have the following imports:
import alertMessages from "../../config/constants/alertMessages";
import buttonTexts from "../../config/constants/buttonTexts";

Ionic 2 - List does not update

I have an ion-list with a ngFor loop. Here is the html:
<ion-list>
<ion-item *ngFor="let kiosk of kiosks" (click)="goToKioskProfilePage(kiosk)">
{{kiosk.name}}
</ion-item>
</ion-list>
And here is the constructor:
kiosks: any;
constructor(public navCtrl: NavController, navParams: NavParams, public locationTracker: LocationTracker, public api: ApiService, public zone: NgZone) {
this.kiosks = [];
this.zone.run(() => {
this.locationTracker.getGeolocation().then(location => {
this.api.getClosestKiosks(location, constants.AMOUNT_OF_CLOSEST_KIOSKS).then(
data => {
console.log("ready");
this.kiosks = data['data'];
},
err => {
console.log(err);
}
);
});
});
}
The console logs "ready" but the list does not update. I already tried it with NgZone but it's still not working. Only when I open the sidemenu the list updates, but not before. Someone know how to fix that?
I've encountered a similar issue before. What fixed it for me was putting only the variable update/assignment in between zone.run(), as it's after the promise resolves that you want to update the values.
Try:
this.locationTracker.getGeolocation().then(location => {
this.api.getClosestKiosks(location, constants.AMOUNT_OF_CLOSEST_KIOSKS).then(
data => {
console.log("ready");
this.zone.run(() => {
this.kiosks = data['data'];
});
},
err => {
console.log(err);
}
);
});

How do you test Collection.allow( ) functions that rely on the user ID?

Given the following collection and access control defintion
class TasksCollection extends Mongo.Collection {
insert (task, callback) {
const doc = _.extend({}, task, {
createdOn: new Date(),
owner: this.userId
})
super.insert(doc, callback)
}
}
export const Tasks = new TasksCollection('tasks')
// Simple checks to ensure that the user is logged in before making changes.
Tasks.allow({
insert: (userId, doc) =>=> !!userId,
update: (userId, doc, fields, modifier) => !!userId,
remove: (userId, doc) => !!userId
})
How would you test to ensure that it works using Mocha/Chai/Sinon? This is what I have tried.
import { Meteor } from 'meteor/meteor'
import { resetDatabase } from 'meteor/xolvio:cleaner';
import { assert, expect } from 'chai'
import { Tasks } from '/imports/api/tasks'
import sinon from 'sinon'
describe('collection test', () => {
beforeEach(() => {
resetDatabase()
})
it('can see a collection', () => {
assert(Tasks, 'unable to see sample collection')
})
it('can query an empty collection', () => {
expect(Tasks.find({}).fetch()).to.be.empty
})
it('fails to add to a collection when the user is not logged in', (done) => {
expect(Tasks.find({}).fetch()).to.be.empty
Tasks.insert({
text: 'hello world'
}, (error) => {
console.log('expected', error) // this is also a 404
assert(error)
done()
})
})
describe('logged in', () => {
let sandbox
beforeEach(() => {
sandbox = sinon.sandbox.create()
sandbox.stub(Meteor, 'userId').returns(42)
})
afterEach(() => {
sandbox.restore()
})
it('can add to a collection', (done) => {
expect(Tasks.find({}).fetch()).to.be.empty
Tasks.insert({
text: 'hello world'
}, (error, _id) => {
console.log(error)
assert(!error)
const results = Tasks.find({}).fetch()
expect(results).to.have.lengthOf(1)
expect(results[0].defaultValue).to.equal(42)
expect(results[0]._id).to.equal(_id)
expect(results[0].createdOn).to.not.be.undefined
done()
})
})
})
})
UPDATE: But I get a 404 error when calling the server.
The insecure package is already removed.
UPDATE: I am only testing on the client for now as the authorization can only be done from a client call.

angular2 - how to simulate error on http.post unit test

I m writing a Uni-test for a login Method with an HTTP.post call, like:
this.http.post( endpoint, creds, { headers: headers})
.map(res => res.json())
.subscribe(
data => this.onLoginComplete(data.access_token, credentials),
err => this.onHttpLoginFailed(err),
() => this.trace.debug(this.componentName, "Login completed.")
);
The problem is that i'm not able to simulate the error branch; everytime is called the onLoginComplete Method;
here is my test:
it("check that Atfer Login, console show an error ", inject(
[TraceService, Http, MockBackend, WsiEndpointService],
(traceService: TraceService, http: Http,
backend: MockBackend, wsiEndpoint: WsiEndpointService) => {
let tokenTest: number = 404 ;
let response: ResponseOptions = null {} // i think i have to modify this
let connection: any;
backend.connections.subscribe((c: any) => connection = c);
let authService: AuthService = new AuthService(http, Service1, Service2);
authenticationservice.login({ "username": "a", "password": "1" });
connection.mockRespond(new Response(response));
expect(ERROR);
}));
Thanks again to everyone.
First you need to override the XHRBackend class by the MockBackend one:
describe('HttpService Tests', () => {
beforeEachProviders(() => {
return [
HTTP_PROVIDERS,
provide(XHRBackend, { useClass: MockBackend }),
HttpService
];
});
(...)
});
Notice that HttpService is the service that uses the Http object and I want to test.
Then you need to inject the mockBackend and subscribe on its connections property. When a request is sent, the corresponding callback is called and you can specify the response elements like the body. The service will receive this response as the response of the call. So you'll be able to test your service method based on this.
Below I describe how to test the getItems method of the HttpService:
it('Should return a list of items', inject([XHRBackend, HttpService, Injector], (mockBackend, httpService, injector) => {
mockBackend.connections.subscribe(
(connection: MockConnection) => {
connection.mockRespond(new Response(
new ResponseOptions({
body: [ { id: '1', label: 'item1' }]
})));
});
httpService.getItems().subscribe(
items => {
expect(items).toEqual([ { id: '1', label: 'item1' }]);
});
});
});
Here is the code of getItems method of the HttpService:
#Injectable()
export class HttpService {
constructor(private http:Http) {
}
getItems(): Observable<any[]> {
return this.http.get('/items').map(res => res.json());
}
}
To simulate an error simply use the mockError method instead of the mockResponseone:
mockBackend.connections.subscribe(
(connection: MockConnection) => {
connection.mockError(new Error('some error'));
});
You can simulate an error like this:
connection.mockError(new Response(new ResponseOptions({
body: '',
status: 404,
})));
I created a small class
import {ResponseOptions, Response} from '#angular/http';
export class MockError extends Response implements Error {
name: any;
message: any;
constructor(status: number, body: string = '') {
super(new ResponseOptions({status, body}));
}
}
which can use like this
connection.mockError(new MockError(404));