How to use withVariables method in pact-foundation-pact

Best JavaScript code snippet using pact-foundation-pact

query-builder.ts

Source:query-builder.ts Github

copy

Full Screen

1import { gql } from 'js/graphql'2import { Model, ModelArray, StaticModel, Type } from 'js/model/model'3import { str_random } from 'js/util'4import escapeRegExp from 'lodash/escapeRegExp'5import map from 'lodash/map'6interface Where {7 field: string8 value: string | number | boolean9 type: Type10}11export interface GetOptions {12 cache?: boolean13 network?: boolean14 save?: boolean15}16export class QueryBuilder<T extends Model> {17 private TClass: StaticModel<T>18 private wheres: Where[] = []19 private selects: string[] = []20 private withs: Array<QueryBuilder<any>> = []21 private _skip: number = 022 private _take: number = 10023 private _sort: string[] = []24 constructor(TClass: StaticModel<T>) {25 this.TClass = TClass26 }27 public clone(): QueryBuilder<T> {28 const qb = new QueryBuilder<T>(this.TClass)29 qb.TClass = this.TClass30 qb.wheres = this.wheres.slice(0)31 qb.selects = this.selects.slice(0)32 qb.withs = this.withs.slice(0)33 qb._skip = this._skip34 qb._take = this._take35 qb._sort = this._sort36 return qb37 }38 public where(field: keyof T, value: string | number | boolean | RegExp): QueryBuilder<T> {39 const type: Type = this.TClass.types[field as string] || this.TClass.searchTypes[field as string]40 if (value instanceof RegExp) {41 value = value.source42 } else if (typeof value === 'string' && type.type === 'String') {43 value = '^' + escapeRegExp(value) + '$'44 }45 const where: Where = {46 field: field as string,47 value: value,48 type: type,49 }50 if (field === 'search') {51 where.type = { type: 'String', jsType: undefined }52 }53 if (field === 'before' || field === 'after') {54 where.type = { type: 'ID', jsType: undefined }55 }56 this.wheres.push(where)57 return this.clone()58 }59 public select(...selects: Array<keyof T>): QueryBuilder<T> {60 this.selects = this.selects.concat(selects as string[])61 return this.clone()62 }63 public skip(skip: number): QueryBuilder<T> {64 this._skip = skip65 return this.clone()66 }67 public take(take: number): QueryBuilder<T> {68 this._take = take69 return this.clone()70 }71 public sort(...column: string[]): QueryBuilder<T> {72 this._sort = this._sort.concat(column)73 return this.clone()74 }75 public with(...qb: Array<QueryBuilder<any>>): QueryBuilder<T> {76 this.withs = this.withs.concat(qb)77 return this.clone()78 }79 public getQuery(prefix?: string): [string, Dictionary<string>, Dictionary<string | number | boolean>] {80 const types: Dictionary<string> = {}81 const variables: Dictionary<string | number | boolean> = {}82 let withTypes: Dictionary<string> = {}83 let withVariables: Dictionary<string | number | boolean> = {}84 let selects: string[] = []85 for (const where of this.wheres) {86 const field = where.field87 variables[field] = where.value88 if (field === 'search') {89 types[field] = 'String'90 } else {91 switch (where.type.type) {92 case 'String':93 types[field] = 'Regex'94 break95 case 'Int':96 case 'Float':97 types[field] = 'NumberRange'98 break99 default:100 types[field] = where.type.type101 }102 }103 }104 if (this._sort.length > 0) {105 types.sort = 'String'106 variables.sort = this._sort.join(',')107 }108 if (this.selects.length === 0) {109 selects = this.generateGQL(this.TClass)110 } else {111 for (const select of this.selects) {112 const type = this.TClass.types[select]113 if (type.jsType === undefined) {114 selects.push(select)115 } else {116 selects.push(`${select} {${this.generateGQL(type.jsType).join(', ')}}`)117 }118 }119 }120 const withSelects: string[] = []121 for (const qb of this.withs) {122 const [q, t, v] = qb.getQuery(str_random(5))123 withSelects.push(q)124 withTypes = { ...withTypes, ...t }125 withVariables = { ...withVariables, ...v }126 }127 variables.take = this._take128 types.take = 'Int!'129 variables.skip = this._skip130 types.skip = 'Int'131 if (prefix) {132 for (const name in types) {133 if (types.hasOwnProperty(name)) {134 types[`${prefix}_${name}`] = types[name]135 delete types[name]136 }137 }138 for (const name in variables) {139 if (variables.hasOwnProperty(name)) {140 variables[`${prefix}_${name}`] = variables[name]141 delete variables[name]142 }143 }144 }145 const vars = map(types, (_, key) => `${key.replace(prefix + '_', '')}: $${key}`).join(', ')146 const query = `${this.TClass.table} (${vars}) {147 total148 results {149 ${selects.concat(withSelects).join('\n ')}150 }151 }`152 // console.log(query);153 return [154 query,155 { ...types, ...withTypes },156 { ...variables, ...withVariables },157 ]158 }159 public async get(options: GetOptions = {}): Promise<ModelArray<T>> {160 const defaults: GetOptions = {161 cache: false,162 network: true,163 save: false,164 }165 options = { ...defaults, ...options }166 const [query, types, variables] = this.getQuery()167 const gqlFetch = gql(query, types, variables) // start fetching before checking the local cache168 // console.log('get', query, types, variables)169 const data = await gqlFetch170 return this.buildResult(this.TClass, data)171 }172 public async first(options: GetOptions = {}): Promise<T> {173 this.take(1)174 const models = await this.get(options)175 return models[0] || null176 }177 public generateGQL(jsType: any): string[] {178 return map(jsType.types, (type, key) => {179 if (type.writeOnly) {180 return181 }182 if (type.jsType === undefined) {183 return key184 }185 if (type.jsType.prototype instanceof Model) {186 return187 // return `${key} (take: 1) {${this.generateGQL(type.jsType).join(', ')}}`188 }189 return `${key} {${this.generateGQL(type.jsType).join(', ')}}`190 }).filter(select => select !== undefined) as string[]191 }192 private buildResult(jsType: StaticModel<any>, data: any): ModelArray<T> {193 const elements: T[] = []194 for (const element of [].concat(data.results) as any[]) {195 map(jsType.types, (type, key) => {196 if (!element[key]) { return }197 if (type.jsType && type.jsType.prototype instanceof Model) {198 element[key] = this.buildResult(type.jsType, element[key])199 } else if (type.type === 'DateTime') {200 element[key] = new Date(element[key])201 }202 })203 elements.push(new jsType(element, true))204 }205 return new ModelArray(elements, {206 total: data.total,207 skip: this._skip,208 take: this._take,209 })210 }...

Full Screen

Full Screen

spec.js

Source:spec.js Github

copy

Full Screen

1/* globals describe, it, beforeEach */2/* eslint-disable no-sequences */3const chai = require('chai')4chai.use(require('chai-as-promised'))5const { expect } = chai6const schema = require('./index')7function expectData ({data, errors}) {8 expect(errors).to.not.exist9 expect(data).to.be.an('object')10 return data11}12describe('merging @skip and @include', () => {13 // behavior as defined in14 // https://github.com/facebook/graphql/blob/master/spec/Section%203%20--%20Type%20System.md#include15 let include16 let skip17 let queryString18 beforeEach(() => {19 queryString = () => `20 query ($include: Boolean!, $skip: Boolean!) {21 hello @include(if: ${include}) @skip(if: ${skip}),22 withVariables: hello @include(if: $include) @skip(if: $skip)23 }24 `25 })26 const variables = () => ({skip, include})27 const result = () => schema.execute(queryString(), variables())28 const assertIncluded = () => result().then(expectData).then(data => {29 expect(data).to.have.property('hello')30 expect(data).to.have.property('withVariables')31 })32 const assertNotIncluded = () => result().then(expectData).then(data => {33 expect(data).not.to.have.property('hello')34 expect(data).not.to.have.property('withVariables')35 })36 describe('when @skip=false and @include=true', () => {37 it('is included', () => {38 skip = false, include = true39 return assertIncluded()40 })41 })42 describe('when @skip=false and @include=false', () => {43 it('is not included', () => {44 skip = false, include = false45 return assertNotIncluded()46 })47 })48 describe('when @skip=true and @include=true', () => {49 it('is not included', () => {50 skip = true, include = true51 return assertNotIncluded()52 })53 })54 describe('when @skip=true and @include=false', () => {55 it('is not included', () => {56 skip = true, include = false57 return assertNotIncluded()58 })59 })60 describe('when evaluating skip on query selection and fragment', () => {61 describe('with @skip', () => {62 beforeEach(() => {63 queryString = () => `64 query ($skip: Boolean!) {65 hello,66 withVariables: hello,67 ...F068 }69 fragment F0 on RootQueryType {70 hello @skip(if: ${skip}),71 withVariables: hello @skip(if: $skip)72 }73 `74 })75 describe('and @skip=false', () => {76 it('is included', () => {77 skip = false78 return assertIncluded()79 })80 })81 describe('and @skip=true', () => {82 it('is included', () => {83 skip = true84 return assertIncluded()85 })86 })87 })88 })89 describe('when evaluating conflicting @skip and @include on query selection and fragment', () => {90 beforeEach(() => {91 queryString = () => `92 query ($include: Boolean!, $skip: Boolean!) {93 hello @include(if: ${include}),94 withVariables: hello @include(if: $include),95 ...F096 }97 fragment F0 on RootQueryType {98 hello @skip(if: ${skip}),99 withVariables: hello @skip(if: $skip)100 }101 `102 })103 describe('when @skip=false and @include=true', () => {104 it('is included', () => {105 skip = false, include = true106 return assertIncluded()107 })108 })109 describe('when @skip=false and @include=false', () => {110 it('is included', () => {111 skip = false, include = true112 return assertIncluded()113 })114 })115 describe('when @skip=true and @include=true', () => {116 it('is included', () => {117 skip = true, include = true118 return assertIncluded()119 })120 })121 describe('when @skip=true and @include=false', () => {122 it('is not included', () => {123 skip = true, include = false124 return assertNotIncluded()125 })126 })127 })128 describe('when handling multiple fields at the same level', () => {129 describe('when at least one occurance would be included', () => {130 beforeEach(() => {131 skip = true, include = false132 queryString = () => `133 query ($include: Boolean!, $skip: Boolean!) {134 hello,135 hello @skip(if: true),136 hello @include(if: false),137 withVariables: hello,138 withVariables: hello @skip(if: $skip),139 withVariables: hello @include(if: $include)140 }`141 })142 it('is included', () => assertIncluded())143 })144 describe('when at no occurance would be included', () => {145 beforeEach(() => {146 skip = true, include = false147 queryString = () => `148 query ($include: Boolean!, $skip: Boolean!){149 hello @skip(if: true),150 hello @include(if: false),151 withVariables: hello @skip(if: $skip),152 withVariables: hello @include(if: $include)153 }`154 })155 it('is not included', () => assertNotIncluded())156 })157 })...

Full Screen

Full Screen

lint.spec.ts

Source:lint.spec.ts Github

copy

Full Screen

1import { version as graphqlVersion } from 'graphql/version';2describe('Linting', () => {3 it('Does not mark valid fields', () => {4 cy.visitWithOp({5 query: /* GraphQL */ `6 {7 myAlias: id8 test {9 id10 }11 }12 `,13 })14 .contains('myAlias')15 .should('not.have.class', 'CodeMirror-lint-mark')16 .and('not.have.class', 'CodeMirror-lint-mark-error');17 });18 it('Marks invalid fields as error', () => {19 cy.visitWithOp({20 query: /* GraphQL */ `21 {22 doesNotExist23 test {24 id25 }26 }27 `,28 }).assertLinterMarkWithMessage(29 'doesNotExist',30 'error',31 'Cannot query field "doesNotExist" on type "Test".',32 );33 });34 it('Marks deprecated fields as warning', () => {35 cy.visitWithOp({36 query: /* GraphQL */ `37 {38 id39 deprecatedField {40 id41 }42 }43 `,44 }).assertLinterMarkWithMessage(45 'deprecatedField',46 'warning',47 'The field Test.deprecatedField is deprecated.',48 );49 });50 it('Marks syntax errors in variables JSON as error', () => {51 cy.visitWithOp({52 query: /* GraphQL */ `53 query WithVariables($stringArg: String) {54 hasArgs(string: $stringArg)55 }56 `,57 variablesString: JSON.stringify({ stringArg: '42' }, null, 2).slice(58 0,59 -1,60 ),61 }).assertLinterMarkWithMessage(62 '"42"',63 'error',64 'Expected } but found [end of file].',65 );66 });67 it('Marks unused variables as error', () => {68 cy.visitWithOp({69 query: /* GraphQL */ `70 query WithVariables($stringArg: String) {71 hasArgs(string: $stringArg)72 }73 `,74 variables: {75 stringArg: '42',76 unusedVariable: 'whoops',77 },78 }).assertLinterMarkWithMessage(79 'unusedVariable',80 'error',81 'Variable "$unusedVariable" does not appear in any GraphQL query.',82 );83 });84 it('Marks invalid variable type as error', () => {85 cy.visitWithOp({86 query: /* GraphQL */ `87 query WithVariables($stringArg: String) {88 hasArgs(string: $stringArg)89 }90 `,91 variables: {92 stringArg: 42,93 },94 }).assertLinterMarkWithMessage(95 '42',96 'error',97 'Expected value of type "String".',98 );99 });100 it('Marks variables with null values for a non-nullable type as error', () => {101 cy.visitWithOp({102 query: /* GraphQL */ `103 query WithVariables($stringArg: String!) {104 hasArgs(string: $stringArg)105 }106 `,107 variables: {108 stringArg: null,109 },110 }).assertLinterMarkWithMessage(111 'null',112 'error',113 'Type "String!" is non-nullable and cannot be null.',114 );115 });116 it('Marks variables with non-object values for a input object type as error', () => {117 cy.visitWithOp({118 query: /* GraphQL */ `119 query WithVariables($objectArg: TestInput) {120 hasArgs(object: $objectArg)121 }122 `,123 variables: {124 objectArg: '42',125 },126 }).assertLinterMarkWithMessage(127 '"42"',128 'error',129 'Type "TestInput" must be an Object.',130 );131 });132 it('Marks GraphQL syntax errors as error', () => {133 cy.visitWithOp({134 query: /* GraphQL */ `135 {136 doesNotExist137 test {138 id139 }140 +++141 }142 `,143 }).assertLinterMarkWithMessage(144 '+++',145 'error',146 graphqlVersion.startsWith('15.')147 ? 'Syntax Error: Cannot parse the unexpected character "+".'148 : 'Syntax Error: Unexpected character: "+".',149 );150 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { eachLike } = require('@pact-foundation/pact').Matchers;2const { SomethingLike } = require('@pact-foundation/pact').Matchers;3const { like } = require('@pact-foundation/pact').Matchers;4const { term } = require('@pact-foundation/pact').Matchers;5const { somethingLike } = require('@pact-foundation/pact').Matchers;6const { uuid } = require('@pact-foundation/pact').Matchers;7const { iso8601DateTimeWithMillis } = require('@pact-foundation/pact').Matchers;8const { like } = require('@pact-foundation/pact').Matchers;9const { somethingLike } = require('@pact-foundation/pact').Matchers;10const { eachLike } = require('@pact-foundation/pact').Matchers;11const { somethingLike } = require('@pact-foundation/pact').Matchers;12const { eachLike } = require('@pact-foundation/pact').Matchers;13const { somethingLike } = require('@pact-foundation/pact').Matchers;14const { eachLike } = require('@pact-foundation/pact').Matchers;15const { somethingLike } = require('@pact-foundation/pact').Matchers;16const { eachLike } = require('@pact-foundation/pact').Matchers;17const { somethingLike } = require('@pact-foundation/pact').Matchers;18const { eachLike } = require('@pact-foundation/pact').Matchers;19const { somethingLike } = require('@pact-foundation/pact').Matchers;20const { eachLike } = require('@pact-foundation/pact').Matchers;21const { somethingLike } = require('@pact-foundation/pact').Matchers;22const { eachLike } = require('@pact-foundation/pact').Matchers;23const { somethingLike } = require('@pact-foundation/pact').Matchers;24const { eachLike } = require('@pact-foundation/pact').Matchers;25const { somethingLike } = require('@pact-foundation/pact').Matchers;26const { eachLike } = require('@pact-foundation/pact').Matchers;27const { somethingLike } = require('@pact-foundation/pact').Matchers;28const { eachLike } = require('@pact-foundation/pact').Matchers;29const { somethingLike } = require('@pact-foundation/pact').Matchers;30const { eachLike

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run pact-foundation-pact automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful