tgriesser / cypress-graphql-mock Goto Github PK
View Code? Open in Web Editor NEWAdds commands for executing a mocked GraphQL server using only the client
Adds commands for executing a mocked GraphQL server using only the client
I'm getting the following error when using cypress-graphql-mock
with @apollo-client
It seems like it doesn't support the standard way @apollo-client makes fetch requests?
Please consider adding support for this.
I tried adding a very quick test myself to see how difficult it is to stub, but it seems straight forward? Even something as simple as this works:
function fetchStub(path, request) {
if (request && request.body) {
// Using operation name of the request to look for response mock data
const { operationName } = JSON.parse(request.body)
Is it possible to mock an applications call to HTTP OPTIONS?
My application under test will fail to load if the calls to OPTIONS are dropped
Examples does:
import schema from '../../../schema.json';
// snip
beforeEach(() => {
// snip
cy.mockGraphql({ schema });
Docs do:
cy.task("getSchema").then(schema => {
cy.mockGraphql({
schema,
operations: { ... }
});
});
There's also a code-generator in the example and a command to update the schema json file. It's unclear:
I am getting the following warning:
Type "Entity" is missing a "__resolveType" resolver. Pass false into "resolverValidationOptions.requireResolversForResolveType" to disable this warning.
We don't have access to makeExecutableSchema
to disable this warning:
const executableSchema = makeExecutableSchema({
typeDefs,
resolvers,
resolverValidationOptions: {
requireResolversForResolveType: false
}
})
We also don't have access to resolvers
to add a workaround:
const resolvers = {
Query: {
// …
},
Node: {
__resolveType() {
return null
}
}
}
I suggest that makeExecutableSchema
should be configurable so that the schema can be configured contextually:
// src/index.ts
Cypress.Commands.add(
"mockGraphql",
<AllOperations extends Record<string, any>>(
options: MockGraphQLOptions<AllOperations>
) => {
const {
endpoint = "/graphql",
delay = 0,
operations = {},
mocks = {}
} = options;
const schema = makeExecutableSchema({
typeDefs: schemaAsSDL(options.schema),
...(options.makeExecutableSchema || {})
});
// ...
Related: apollographql/apollo-server#1075
This plugin isn't working for angular apps because of apollo-angular-link-http
is using xhr
to fetching data. This plugin works only for apollo links which are using fetch
(like this in react).
I guess this info should be included in the readme.
I am importing my schema as one big json object and seeing this error when I try to run the command.
GraphQL error: No mock defined for type "DateTime"
To reproduce, add the custom DateTime scalar as a type to one of your properties.
Hi guys, I'm quite new in GraphQL world and currently I'm facing some difficulties/trouble trying to implement this plugin, If anyone can help, I'll be really thankful .
Problem:
All my mock data fields are returning Hello World
How I'm using this plugin:
In my integration/index.spec.js
context('Get email', () => {
beforeEach(() => {
cy.server();
cy.mockGraphql({ schema });
cy.mockGraphqlOps({
operations: {
GetEmail: {
email: "[email protected]",
}
}
})
});
it('Should mock graphql', () => {
cy.visit('/')
})
})
But I get
{
GetEmail: {
email: 'Hello World'
}
}
Thanks guys ❤️
Not sure if currently is available, if does I would love if we have examples
How can I intercept the stubbed fetch call to inspect the request body?
./node_modules/graphql/index.mjs 42:0-48:205
Can't reexport the named export 'BREAK' from non EcmaScript module (only default export is available)
at HarmonyExportImportedSpecifierDependency._getErrors (src/site/node_modules/webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency.js:363:6)
at HarmonyExportImportedSpecifierDependency.getErrors (src/site/node_modules/webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency.js:343:16)
at Compilation.reportDependencyErrorsAndWarnings (src/site/node_modules/webpack/lib/Compilation.js:1425:22)
at hooks.finishModules.callAsync.err (src/site/node_modules/webpack/lib/Compilation.js:1221:10)
at AsyncSeriesHook.eval [as callAsync] (eval at create (src/site/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:24:1)
at AsyncSeriesHook.lazyCompileHook (src/site/node_modules/tapable/lib/Hook.js:154:20)
at Compilation.finish (src/site/node_modules/webpack/lib/Compilation.js:1216:28)
at hooks.make.callAsync.err (src/site/node_modules/webpack/lib/Compiler.js:662:17)
at _err0 (eval at create (src/site/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:11:1)
at _addModuleChain (src/site/node_modules/webpack/lib/Compilation.js:1148:12)
at processModuleDependencies.err (src/site/node_modules/webpack/lib/Compilation.js:1060:9)
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
@ ./node_modules/cypress-graphql-mock/dist/index.js
@ ./cypress/support/commands.js
@ ./cypress/support/index.js
@ multi ./cypress/support/index.js
When following the readme; 1) install, 2) add import to commands.js, 3) save a .ts
test file.
when trying to make a request I get a ERR_EMPTY_RESPONSE
from the fetch call.
version:0.3.1
This is the code in use.
integration/login.js:
const schema = require('../../schema.json')
context('login', () => {
beforeEach(() => {
cy.mockGraphql({
schema: schema,
endpoint: "/api/task",
})
cy.mockGraphqlOps({
operations: {
userLogin: {
userLogin: {
token: "7b278a718dd147dd912f9d542540bd09",
userId: 1080,
orgId: 1013,
name: "账务",
avatar: "",
needInitOrg: false,
__typename: "UserLoginResp"
}
},
getUserInfo: {
personalInfo: {
data: {
user: {
id: 1080,
loginName: "18891111112",
name: "张三三",
sex: 99,
email: "",
avatar: "",
level: 1,
levelName: "试用级别",
rimanente: 10,
emplId: "",
orgId: 1013,
orgName: "星星电灯水水水水",
orgCode: "",
mobile: "18891111112",
thirdName: "",
birthday: "1970-01-01 00:00:00",
passwordSet: 1,
isAdmin: false,
remindBindPhone: 2,
functions: [],
__typename: "PersonalInfo"
}
}
}
}
}
});
})
})
This is the code in use.
support/command.js:
import "cypress-graphql-mock";
When following the getting started example and registering an op, you get this error:
"Expected { __schema: { queryType: [Object], mutationType: [Object], subscriptionType: [Object], types: [Array], directives: [Array] } } to be a GraphQL schema."
Seemingly from this plugin. This is the code in use:
/// <reference types="Cypress" />
import schema from '../../../schema.json'
context("app inbox", () => {
before(() => {
cy.request('POST', '/api/accounts/seed', { failOnStatusCode: true })
})
beforeEach(() => {
cy.server()
cy.mockGraphql({
schema
})
})
it("shows", () => {
cy.url().should('include', '/app/inbox')
})
it.only('renders inbox items', () => {
cy.mockGraphqlOps({
operations: {
fetchInboxItems: {
inbox: [ {
__typename: 'Notice',
id: '123',
urgency: 'urgent',
importance: 'important',
title: "Testing",
description: 'Testing desc'
} ]
}
}
})
cy.visit('/app/inbox')
cy.log('using schema', schema)
})
})
Which results in this inside Cypress/the app:
And the error
property in the Apollo client being a non-null, non-undefined value, with the same error string.
The schema.json
is being fetched with, before running the tests:
apollo schema:download --endpoint=http://127.0.0.1:3000/graphql
with cy.task you can't pass mocks as functions
this works really well for me:
import { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';
import { print } from 'graphql/language/printer';
import { graphql } from 'graphql';
Cypress.Commands.add(
'graphql',
({ query, resolvers, mocks, preserveResolvers = true }) =>
cy.readFile('schema.graphql').then(typeDefs => {
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
addMockFunctionsToSchema({
schema,
mocks,
preserveResolvers,
});
return graphql(schema, print(query)).then(value => {
console.dir({ value }, { depth: Infinity });
return value;
});
})
);
however I don't know how to mock cy.route for multiple requests since its the same URL
I have some queries which call the same field with different arguments and use an alias to remap the field names for the duplicate fields in the query. This behavior is not possible to replicate in cy.mockGraphqlOps({operations: {...}})
.
See a potential query here:
query ChannelsQuery{
me{
_id
canCreateChannels: hasPerm(entity:"channel" action:"create")
canViewChannels: hasPerm(entity:"channel" action: "read")
}
...
}
if I provide the operation value:
cy.mockGraphqlOps({
operations: {
...baseOperations,
ChannelsQuery: {
me: {
...me,
hasPerm: false,
},
...
}
}
});
This will set canCreateChannels
and canViewChannels
both as false, but there is no way to set the alias values individually.
Our ApolloClient receives two parallel GQL endpoints and our queries are resolving to them.
Tried to provide endpoint
for multiple mockGraphql
methods or defining on a task, but so far no luck with it.
Do you have any suggestion to approach this, with a maintainable manner?
From using the typescript example recipe, adding the import statement for cypress-graphql-mock breaks the registration of new methods. File: https://github.com/cypress-io/cypress-example-recipes/blob/master/examples/preprocessors__typescript-webpack/cypress/support/commands.ts
I'm not able to use this module due to this feature being disabled. Rather than doing all of the cypress type registration and method adding in the imported file, this module could expose the type definitions and methods so that they can be bound in a declare namespace statement as per the recipe
Edit:
The commands.ts supplied in the example by cypress is an internal module, to work together with cypress-graphql-mock you need to move the commands.ts file elsewhere to allow it to remain as an internal module, and create a new commands.ts file which imports both cypress-graphql-mock and the moved commands.ts
// commands.ts
import 'cypress-graphql-mock';
import './custom-commands';
Maybe this should be noted in the read me for typescript users
Hey guys,
Do you think it worths adding more examples on README regarding the integration with graphql-tools
? It took some time to me to understand how to add my custom scalars on mockGraphql
, even though it is pretty straightforward I had to took a look at the source to have a clear understanding on it. :)
Are there any examples of using this plugin with fs.readFileSync
? I'd prefer to read in the graphql schema than import a json introspection query.
When specifying an endpoint, an error is produced:
beforeEach(() => {
cy.server();
cy.mockGraphql({
schema: Cypress.env("GRAPHQL_SCHEMA"),
endpoint: "/api"
});
});
produces error:
CypressError: cy.get() could not find a registered alias for: '@mockGraphqlOps'.
Available aliases are: 'mockGraphqlOps:/api'.
Changing the cy.mockGraphql()
call to the following resolves the issue:
beforeEach(() => {
cy.server();
cy.mockGraphql({
schema: Cypress.env("GRAPHQL_SCHEMA"),
endpoint: "/api"
}).as("mockGraphqlOps");
});
If this is normal expected behavior, a note in the readme should be added to add .as(). As a newer user of Cypress this tripped me up.
What the title says? Is it time to fork it and hand it over to someone who maintains it?
I ran into a spooky issue when using graphql-tools' MockList
to mock lists in my schema, where as soon as I returned a MockList
in my mocks
or operations
object, I'd get an error like this:
GraphQL error: Expected Iterable, but did not find one for field Query.things.
Here's an example Cypress test snippet that reproduces this error:
import schema from '../schema.json';
import { MockList } from 'graphql-tools';
describe('Example', () => {
beforeEach(() => cy.mockGraphql({ schema }));
it('Results in an error', () => {
cy.mockGraphqlOps({
operations: {
ExampleQuery: {
things: [], // returning an empty array works fine...
},
AnotherExampleQuery: {
things: new MockList(9), // but this doesn't!
},
},
});
The error above gets thrown here, because the result instanceof MockList
condition always returns false
when trying to build the mocked GraphQL response (even though logging result
to the console clearly shows it as a MockList
).
I believe this is an issue with objects that "travel" between the main Cypress test runner & the actual page via the window:before:load
event or the invoke
command, since using instanceof
to compare objects created in a different window will always return false
. (See also: similar issues described in cypress-io/cypress#3420 and cypress-io/cypress#2794.)
Those experienced with Cypress may realize this, but I think it's worth mentioning you also need to update commands.js
with:
import 'cypress-graphql-mock';
Thanks for the plugin! I tried it out with my app and it fails on pages where there are multiple graphql queries batched in a single request (one of the strengths of graphql). It manifested as this TypeError: Must provide Source
because payload.query
was undefined (payload was an array).
https://www.apollographql.com/docs/link/links/batch-http.html
I believe you need to handle when the payload is an array here: https://github.com/tgriesser/cypress-graphql-mock/blob/master/src/index.ts#L101
And just return a single Response.
cypress-graphql-mock/src/index.ts
Line 169 in edca295
this line should be executable schema as on previous versions.
I have been successfully running cypress-graphql-mock for a while and since updating to cypress 3.8.3 I am getting the error for all my stubs Promise {<rejected>: Error: Expected "type
has anyone encountered this error before. I have tried updating the schema but have not had much luck debugging the issue
any help would be much appreciated
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.