How to add before:spec hook in cypress cucumber framework - cypress

getListOfPlans() {
return new Cypress.Promise((resolve) => {
usersUtil.getCurrentCompany().then((company) => {
cy.request({
method: 'GET',
url: `${TrainingPlanApi.baseTrainingPlanApiUrl}/company/${company.id}/plan`,
}).then((resp) => {
expect(resp.status).to.eq(200);
cy.wrap(resp.body.data).as('existingTrainingPlans');
resolve(resp.body.data);
});
});
if (this.environment === 'local') {
trainingTrainingPlanListPage.visit();
} else {
mainMenu.openTrainingPlans();
trainingPlanApi.getListOfPlans().then((data) => {
cy.get(`#existingTrainingPlans`).each((planData) => {
const plan = planData as unknown as TrainingPlan;
trainingPlanApi.delete(plan.ksuid);
});
});
}
}) as unknown as Chainable<TrainingPlanRequest>;
i need to call the above api function in the before:spec
on('before:spec', async (spec) => {
getListOfPlans
});
but the above doesnt work, not sure how to solve this please

First, you need to link your function to a custom command, in this way:
Cypress.Commands.add('getListOfPlans', getListOfPlans)
Then, you can invoke that command in your before hook, in this way:
Before(() => {
cy.getListOfPlans()
})
Note: The function and the custom command should be in the same file, or import the function into the file where the command is declared.

Related

Laravel route group with variable prefix and where condition

I would like to create a route group in Laravel with a variable as a prefix. I need to set certain conditions too. How to do it properly?
I was following docs: https://laravel.com/docs/8.x/routing#route-group-prefixes but there are only general examples.
This code should create 2 routes: /{hl}/test-1 and /{hl}/test-2 where {hl} is limited to (en|pl), but it gives an error: "Call to a member function where() on null"
Route::prefix('/{hl}')->group(function ($hl) {
Route::get('/test-1', function () {
return 'OK-1';
});
Route::get('/test-2', function () {
return 'OK-2';
});
})->where('hl','(en|pl)');
The group call doesn't return anything so there is nothing to chain onto. If you make the where call before the call to group, similarly to how you are calling prefix, it will build up these attributes then when you call group it will cascade this onto the routes in the group:
Route::prefix('{hl}')->where(['h1' => '(en|pl)'])->group(function () {
Route::get('test-1', function () {
return 'OK-1';
});
Route::get('test-2', function () {
return 'OK-2';
});
});
By analogy with this answer:
Route::group([
'prefix' => '{hl}',
'where' => ['hl' => '(en|pl)']
], function ($hl) {
Route::get('/test-1', function () {
return 'OK-1';
});
Route::get('/test-2', function () {
return 'OK-2';
});
});
Does this solve your problem?

How to make a form validation in InertiaJS

I am follow this Link for a inertiaJS tutorial. BTW I'm using laravel 8
I have this image below from my webpage. I don't know why I don't have a page>errors in picture given. Is there any other way to validate a form other than the link that I provided?.
I commented out the page.error in my HTML because it causes me an error Error in render: "TypeError: Cannot read property 'email' of undefined" because of my Page.Error is an empty object.
Update : Code for my controller
Script Code
<script>
import Layout from "../../Shared/Layout";
export default {
components: {
Layout,
},
data() {
return {
lead: {
name: "",
email: "",
phone: "",
dob: "",
interested_package: "",
},
};
},
methods: {
async handleSubmit() {
let res = await this.$inertia.post("/leads/save", this.lead);
},
},
};
</script>
App Service Provider
public function boot()
{
//
Schema::defaultStringLength(255);
Inertia::share([
'errors' => function () {
return Session::get('errors')
? Session::get('errors')->getBag('default')->getMessage()
: (object)[];
}
]);
Inertia::share('flash', function () {
return [
'message' => Session::get('message'),
'success' => Session::get('success'),
'error' => Session::get('error'),
];
});
}
To access the email error, context needs to be added via the this keyword ie. this.$page.props.errors.email.
Hey i think you are not sharing error bag in Controller that is why is empty ,to solve this, go to your AppServiceProvider
and add this code.
Inertia::share([
'errors' => function () {
return Session::get('errors')
? Session::get('errors')->getBag('default')->getMessages()
: (object) [];
},
]);

How to download Laravel Excel with Ajax method

I'm working on Laravel Excel using Ajax method. Below is my controller.
public function downloadExcel(){
return Excel::download(new SomeExport(), 'project.xlsx');
}
And this is ajax call.
$(document).on('click', '#download_excel', function(e) {
downloadExcel().then(data => {
//may be need to do some here.
}).catch(error => {})
});
function downloadExcel() {
return new Promise((resolve, reject) => {
$.ajax({
url: `${route.url}/api/...`,
type: 'GET',
headers: {"X-CSRF-TOKEN":route.token},
success: function(data) {
resolve(data)
},
error: function(error) {
reject(error)
},
})
})
}
This work for normal request but not work for ajax. Any advice or guidance on this would be greatly appreciated, Thanks.
I've tried this, and it works.
$(document).on('click', '#download_excel', function(e) {
window.location="{{ route('yourRoute')}}";
})

On get request why do I get back the blade view, when I should get data from the database instead?

I a have the following get request, which is executed on mounted().
In some weird mysterious ways, I get back my main view app.blade as a response when I am clearly requesting some data from the database.
Can someone spot what I messed up?
My get request on the front-end:
mounted() {
this.getProjectRequests();
},
methods: {
getProjectRequests: function() {
var self = this;
let clientId = this.$route.path.substring(
this.$route.path.lastIndexOf("/") + 1
);
axios({
method: "get",
url: "/get-project-requests/" + clientId
})
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
// TODO error handling
});
}
}
My route:
Route::get('/get-project-requests/{client_id}',
'SinglePageController#getProjectRequests');
And my controller method:
public function getProjectRequests($clientId) {
try {
$projectRequests = ProjectRequest::where('client_id',
$clientId)->value('name');
return response()->json( [
'success'=> true,
'projectRequests' => $projectRequests
]);
} catch(\Exception $e){
return ['success' => false, 'message' => 'getting
project requests failed'];
}
}
I think this ProjectRequest::where('client_id', $clientId)->value('name'); giving exception.
Either you check your laravel.log inside storage/logs folder or change that method into
// Not working on eloquent model
$valueOject = ProjectRequest::where('client_id',$clientId)->value('name');
// DB facade its working. Change to this method
$valueOject = DB::table('{your_table}')->where('client_id', $clientId)->value('name');
dd($valueOject);

Redux Observable: How to return an action inside promise?

I have an epic:
export default function uploadImage(action$, store) {
return action$.ofType(userActions.UPLOAD_IMAGE)
.mergeMap(action => {
...
RNFetchBlob.fs.readFile(uploadUri, 'base64').then(data => {
firebaseRef.putString(data).then(snapshot => {
console.log('Uploaded a blob or file!');
return Observable.of(userActions.updateImageURL(snapshot.downloadURL)); //<----------
})
});
})
};
However, this throws You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable. with reason.
How would I wrap the callbacks inside an observable so that the epic doesn't break?
In additionl to Maxime answer, in your example it appears the actual issue is that you're not really returning the Promise! You need to either return it or switch to using implicit return syntax for arrows
export default function uploadImage(action$, store) {
return action$
.ofType(userActions.UPLOAD_IMAGE)
.mergeMap(action => {
return Observable // don't forget to return this chain!
.fromPromise(RNFetchBlob.fs.readFile(uploadUri, 'base64'))
.map(data => {
firebaseRef.putString(data).then(snapshot => {
console.log('Uploaded a blob or file!');
return userActions.updateImageURL(snapshot.downloadURL);
})
});
This is a very common mistake, we've all been there!
Probably something like that :
export default function uploadImage(action$, store) {
return action$
.ofType(userActions.UPLOAD_IMAGE)
.mergeMap(action => {
...
Observable
.fromPromise(RNFetchBlob.fs.readFile(uploadUri, 'base64'))
.map(data => {
firebaseRef.putString(data).then(snapshot => {
console.log('Uploaded a blob or file!');
return userActions.updateImageURL(snapshot.downloadURL);
})
});

Resources