Ember.js - ember-pikaday not resolving American dates? - ember.js

I am trying to pass a replacement datepicker on the site with the geb tests we are running.
it is failing on handling an American mock test
{{pikaday-input
value=localisedValue
format=(if format format "DD/MM/YYYY")
name=name
placeholder=localisedPlaceholder
onSelection=(action setValue)
id=inputId
classNames="date-placeholder"
tabindex=tabIndex
}}
date.js
import LocalisedTextInput from './localised-text-input';
export default LocalisedTextInput.extend({
setValue(dateValue) {
if(dateValue) {
let valueFormat = this.get('valueFormat') ? this.get('valueFormat') : 'YYYY-MM-DD';
if(valueFormat !== 'date') {
dateValue = window.moment(dateValue).format(valueFormat);
}
else {
dateValue = window.moment(dateValue);
}
}
this.set('localisedValue', dateValue);
}
});
and the test
def "Agenda Day renders correctly in the US"() {
given:
bootstrapPublishedTestEvent()
and:
def page = asyncTo EditAgendaPage, siteUnderTest
when:
page.mockTimeZone(420)
page.addDay('20/02/2016', 'Day 1')
then:
page.days*.date == ["20/02/2016"]
}
when I comment out page.mockTimeZone(420) -- the test passes.
mockTimeZone is using the TimeShift.js lib
Date = TimeShift.Date;
TimeShift.setTimezoneOffset(420);
there is a bug that if the date from the server is 31/12/2019 - in UK timezone it is correct -- but in the US timezone it shows as 30/12/2019

Related

How to get the currentUser provided by spring security in Grails 2 unit testing

Hi guys i am on trouble about getting the current user provided by spring.
Here's my unit test code
void "Test if adding project will sucess"() {
given:
def createProjectMock = mockFor(UserService)
createProjectMock.demand.createNewProject { Map projectMap ->
return true
}
controller.userService = createProjectMock.createMock()
when: "saveProject is execute"
controller.saveProject()
then: "page will to the list to view the saved project"
response.redirectedUrl == '/user/index2'
}
Here's my controller
def saveProject(ProjectActionCommand projectCmd) {
def currentUser = springSecurityService.currentUser
if (projectCmd.hasErrors()) {
render view: 'createProject', model: [projectInstance: projectCmd, user:currentUser]
} else {
def getProjectMap = [:]
getProjectMap = [
projectName: params.projectName,
user: currentUser
]
def saveProject = userService.createNewProject(getProjectMap)
if (saveProject) {
redirect view: 'index2'
} else {
render 'Error upon saving'
}
}
}
And here's my service
Project createNewProject(Map projectMap){
def createProject = new Project()
createProject.with {
projectName = projectMap.projectName
user = projectMap.user
}
createProject.save(failOnError:true, flush: true)
}
And i always getting this error:
Cannot get property 'currentUser' on null object.
Hope you can help me. Thanks
Cannot get property 'currentUser' on null object.
means that you haven't mocked springSecurityService. Let's do it in setup section (I assume it may be useful also in other methods in this class):
def springSecurityService
def setup() {
springSecurityService = Mock(SpringSecurityService)
controller.springSecurityService = springSecurityService
}
At this point your code is going to work. However remember that you can always mock also the actual logged user and test it at any point:
User user = Mock(User)
springSecurityService.currentUser >> user

Unknown field `edges` on type `Query`

I am getting the error from the title when I attempt to run relay-compiler in my project. I am using graphql-python/graphene-django for the back end graphql server. Here's an abbreviated copy of my schema.
grove.gql_schema.py:
from graphene_django import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField
from .models import Tree
class TreeNode(DjangoObjectType):
class Meta:
model = Tree
filter_fields = ['owner']
interfaces = (relay.Node,)
class Query(ObjectType):
def resolve_my_trees(self, info):
if not info.context.user.is_authenticated:
return Tree.objects.none()
else:
return Tree.objects.filter(owner=info.context.user)
my_trees = DjangoFilterConnectionField(TreeNode)
tree = relay.Node.Field(TreeNode)
project.gql_schema:
class Query(grove.gql_schema.Query, graphene.ObjectType):
pass
schema = graphene.Schema(query=Query)
With that setup, I can successfully run the following query in GraphiQL
query {
myTrees {
edges {
node {
id
}
}
}
}
So far so good, but now I'm trying to build a client-side component that can use this query.
jsapp/components/index.jsx:
import React from 'react';
import {graphql, QueryRenderer} from 'react-relay';
import environment from '../relay_env'
const myTreesQuery = graphql`
query componentsMyTreesQuery {
edges {
node {
id
}
}
}
`;
export default class App extends React.Component {
render() {
return (
<QueryRenderer
environment={environment}
query={myTreesQuery}
variables={{}}
render={({error, props}) => {
if (error) {
return <div>Error!</div>;
}
if (!props) {
return <div>Loading...</div>;
}
return <div>User ID: {props.edges}</div>;
}}
/>
);
}
}
The query is identical, but when I run relay-compiler --src ./jsapp --schema ./schema.graphql --extensions js jsx I get the error:
GraphQLParser: Unknown field `edges` on type `Query`.
Source: document `componentsMyTreesQuery` file: `components/index.jsx`.
I get this error if when I use the .json schema generated by the Django graphaql_schema management command or the .graphql one retrieved by get-graphql-schema.
What part am I missing?
I might be a bit late but it looks to me like you're trying to ask for the edges on the root of your schema, the fragment:
const myTreesQuery = graphql`
query componentsMyTreesQuery {
edges {
node {
id
}
}
}
`;
I think could be altered to:
const myTreesQuery = graphql`
query componentsMyTreesQuery {
myTrees {
edges {
node {
id
}
}
}
}
`;
The text after the keyword query refers to the name of the 'query', not the root of the schema. If you're using Relay Modern (which by the use of QueryRenderer, I assume you are) then the compiler should yell at you to fix the name of your fragment to something that reflects the filename that it's stored in.

How can I unit test a controller using altered default date binding?

How can I simulate the behavior of grails.databinding.dateFormats in a controller spock test?
In my Config.groovy, I added these settings:
grails.databinding.dateFormats = [
'yyyy-MM-dd\'T\'HH:mm:ss.SSSX',
'yyyy-MM-dd\'T\'HH:mm:ssX',
]
What do I have to do to get the unit test framework to bind date properties using one of the specified formats?
My controller looks like:
class MyController {
static responseFormats = ['json']
def get() {
MyCommand command = bindData(new MyCommand(), params)
command.validate()
if (command.hasErrors()) {
...
}
else {
//...do stuff with command object
}
}
#Validateable
class MyCommand {
Long resourceId
Date startDate
Date endDate
static constraints = {
resourceId nullable: false
startDate nullable: false
endDate nullable: false
}
}
}
When I run the application, this code works normally; however, when bindData() is called in the unit test, the 'resourceId' property on the command object is populated, while the date properties are not.

grails Unit test spock issue

i am new to grails.
i just scaffold a domain class employee, which given below
class Employee {
String firstName
String lastName
static constraints = {
}
}
I am trying to write a unit test on list action in EmployeeController using spock. The controller is given below
class EmployeeController {
static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
def index() {
redirect(action: "list", params: params)
}
def list(Integer max) {
params.max = Math.min(max ?: 10,100)
[employeeInstanceList: Employee.list(params), employeeInstanceTotal: Employee.count()]
}
}
then i wrote a test case given below
import grails.test.mixin.TestFor
import spock.lang.Specification
#TestFor(EmployeeController)
class EmployeeControllerUnitSpec extends Specification {
def 'test index'() {
when:
controller.index()
then:
// httpcode ? 200
//println response (GrailsMockHttpServletResponse)
response.redirectedUrl == '/employee/list'
}
def 'test list empty'() {
when:
controller.list( 10 )
// Employee.list()
then:
model.employeeInstanceTotal == 0;
}
}
Here test case for index works correctly ,but test for list empty render some error in console.
The error decription in console is
| Running 2 spock tests... 2 of 2
| Failure: test list empty(com.test.EmployeeControllerUnitSpec)
| groovy.lang.MissingMethodException: No signature of method: com.test.Employee.list() is applicable for argument types: () values: []
Possible solutions: list(), list(java.util.Map), last(), last(java.lang.String), last(java.util.Map), first()
at com.test.EmployeeController.list(EmployeeController.groovy:15)
at com.test.EmployeeControllerUnitSpec.test list empty(EmployeeControllerUnitSpec.groovy:21)
| Completed 2 spock tests, 1 failed in 3231ms
| Tests FAILED - view reports in /mnt/hdd2/home/T-2060/workspace/testing/target/test-reports
Can any one suggest , how can resolve this issue
thankz in advance
Unit test environment will not have the domain available until it is mocked.
Use #Mock(Employee) and setup test data in Employee to test list() action.

Unit testing custom validator of command object with dependency

I have a command object for registering user, and I want to check how old is the user. This command object has a service dependency. How can I test custom validator for my dateOfBirth property? As it looks now is taken straight from documentation, here.
class RegisterUserCommand {
def someService
String username
String password
String password2
String email
Date dateOfBirth
static constraints = {
// other constraints
dateOfBirth blank: false, validator: {val, obj ->
return obj.someService.calculateAge(val) >= 18
}
}
So basically the question is: how can I mock 'obj' parameter of the validator closure?
The easiest way to test validation on a command object is to use GrailsUnitTestCase.mockForConstraintsTests. A mock validate method will be applied to your command object, and you can just call validate() like you would outside of a test.
Here's an example of how you could write your unit test. The blank constraint isn't meaningful for dates, so I've changed it to nullable: false.
import grails.test.GrailsUnitTestCase
class RegisterUserCommandTests extends GrailsUnitTestCase {
RegisterUserCommand cmd
protected void setUp() {
super.setUp()
cmd = new RegisterUserCommand()
mockForConstraintsTests RegisterUserCommand, [cmd]
}
void testConstraintsNull() {
cmd.dateOfBirth = null
cmd.someService = [calculateAge: { dob -> 18 }]
def result = cmd.validate()
assert result == false
assert cmd.errors.getFieldErrors('dateOfBirth').code == ['nullable']
}
void testConstraintsCustom() {
cmd.dateOfBirth = new Date()
cmd.someService = [calculateAge: { dob -> 17 }]
def result = cmd.validate()
assert result == false
assert cmd.errors.getFieldErrors('dateOfBirth').code == ['validator.invalid']
}
}
Note that your service won't get injected in a unit test (it will in an integration test though), so you'll either need to mock it, as above, or create an instance and assign it to cmd.someservice.