- Notifications
You must be signed in to change notification settings - Fork1
Mocks network requests and allows you to make assertions about how these requests happened. Supports auto-mocking of graphQL requests given a valid schema.
License
trayio/mock-inspect
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Mocks network requests and allows you to make assertions about how these requests happened. Supports auto-mocking of graphQL requests given a valid schema.
An example using jest:
// Let's imagine we are testing an application in which the user has to login.// We set up a mock for the /login endpoint to not use the real API in our test.constmock=mockRequest({requestPattern:"https://www.yourwebsite.com/login",requestMethod:"POST",responseStatus:201,responseBody:"Welcome!"})// Once the mock is set up, we will execute the application code in our test// which makes a request to the /login endpoint - the response will be mocked.// ... Execute your application code which would perform the login ...// After the request has been executed, we can see how our application made the// request. For our login scenario, we could check that the application// forwards the username and password in the correct format as POST payload.constrequestProps=mock.inspect()expect(requestProps.requestBody).toEqual({username:"Han",password:"Ch3w!3"})
- Installation
- Setting up your test suite
- Available functions and classes
- Using GraphQL
- Unresolved promises in tests, i.e. React tests with jest
- Development
Installing mock-inspect is simple: Fetch it from the npm registry using your favourite package manager, either npm or yarn.
# with npmnpm install --save-dev mock-inspect# with yarnyarn add -D mock-inspect
Our mocking solution has to be set up and torn down accordingly after tests. The methodcleanUpNetworkRequestMocking should run beforeeach of your tests,setUpNetworkRequestMocking()once before all of your tests, andtearDownNetworkRequestMockingonce after all of your tests. How setup steps have to be invoked depends on your test runner. With jest, we would create asetupTestFrameworkFile which would register the following hooks:
const{ cleanUpNetworkRequestMocking, setUpNetworkRequestMocking, tearDownNetworkRequestMocking}=require("mock-inspect")beforeEach(()=>{cleanUpNetworkRequestMocking()})beforeAll(()=>{setUpNetworkRequestMocking()})afterAll(()=>{tearDownNetworkRequestMocking()})
For graphQL APIs, we expose functionality in the setup phase to automatically generate graphQL responses from a schema throughout your entire test suite. (These can be overridden if necessary though). The below example sets up the test suite in such a way so that any graphQL request going againsthttps://thisdomaindoesnotexist.com/graphql will be evaluated against the provided graphQLSchema and an automatic response will be generated.Refer to the type definitions for all available options.
beforeAll(()=>{setUpNetworkRequestMocking({persistentAutoGeneratedGraphQLMocks:[{requestPattern:"https://thisdomaindoesnotexist.com/graphql",graphQLSchema:schemaString,},]})})
By default, network requests that aren't expected to be mocked will throw an error saying that a response handler hasn't been set up for this request. You can disable this behaviour by passing the optionblockUnmockedNetworkRequests: true into thesetUpNetworkRequestMocking method.
setUpNetworkRequestMocking({allowUnmockedRequestsOnNetwork:true})
Please find below a list of available functions and class methods. For detailed examples on how to use each of these, check out ourextensive suite of tests. The types for the possible option objects have been thoroughly annotated - make use of your IDE hints to see the full details for each property.
Mocks a request from scratch using the details you provide.
Receives an object which defines the properties of the request to be mocked and the response to be returned.Check out the type definition for details of properties you can enter.
Returns an instance of theMockedRequest object. You can call available methods from this object to inspect the request.
When creating multiple mocks for the same URL, we will always use the response details of the last call tomockRequest.
const{mockRequest}=require("mock-inspect")// Set up mock:constmock=mockRequest({requestPattern:"https://www.yourwebsite.com/login",requestMethod:"POST",responseStatus:201,responseBody:"Welcome!",responseHeaders:{"Authorization":"take your token good sir!"}})// You can now use all available methods on the MockedRequest class, such as// checking that the request has been made or inspecting which properties have// been used to make it:mock.expectRequestToHaveBeenMade()constrequestProps=mock.inspect()// You can use the requestProps object to make assertions how the request was// made. See 'inspect' in this documentation for more information.
Pass the propertygraphQLMutationName orgraphQLQueryName which should align with the query or mutation you are mocking. For this to work, the graphQL requests by your applicationhave to be made with a JSON payload (content-type: application/json header) that includes thequery property.
constfirstMockedRequest=mockRequest({graphQLMutationName:"FirstMutation",responseBody:"Was set up first",requestMethod:"POST",})constsecondMockedRequest=mockRequest({graphQLQueryName:"SecondQuery",responseBody:"Was set up second",requestMethod:"POST",})// Receives the mocked response "Was set up second" although was called firstawaitrequest(`query SecondQuery { animals { cats } }`)// Receives the mocked response "Was set up first" although was called secondawaitrequest(`mutation FirstMutation(call: "Meow") { id }`)
Every time you mock a request, you get hold of this class which has the following methods:
Returns an object with information about how the network request has been made, using the propertiesrequestBody andrequestHeaders.Check out the type definition for details of the returned properties.
If the request has not been made yet on time of calling.inspect(), an error message will be thrown.
You can use the request information object in any way you like - you could check for equality, test whether the schema matches (i.e. usingjest-json-schema-extended) and many more!
// Set up mock:constmock=mockRequest({requestPattern:"https://www.yourwebsite.com/login",requestMethod:"POST",responseStatus:201,responseBody:"Welcome!",responseHeaders:{"Authorization":"take your token good sir!"}})// ... Execute in your test application code which should make the request ...// Use `inspect()` to retrieve information about how the request has been made.// In the example below, we would use jest's expect method that the request body// included the correct properties and that JSON format was specified in the// request headers. You don't have to use jest's expect though - you can use// the returned object of request information in any way you like!constrequestProps=mock.inspect()expect(requestProps.requestBody).toEqual({username:"Han",password:"Ch3w!3"})expect(requestProps.requestHeaders["content-type"]).toEqual("application/json")
Asserts that the network request you mocked has been called.
constloginRequest=mockRequest({/* mock details go here */})loginRequest.expectRequestToHaveBeenMade()
Asserts that the network request you mocked was not called.
constloginRequest=mockRequest({/* mock details go here */})loginRequest.expectRequestToNotHaveBeenMade()
We also support GraphQL - both for creating mocks and asserting on these mocks.
As outlinedin the section about mockRequest, you have to provide an additional property to pass in the query or mutation name you are mocking so that we know you are mocking a graphQL request.
If desired, we can automatically generate a random graphQL response for you. That way, you don't have to manually define theresponseBody property. To do so, you need to provide us with the graphQL schema of the request that will be made, in the propertygraphQLAutoMocking.schema. (WhengraphQLAutoMocking.schemaandresponseBody is given, we will always use theresponseBody property.)
Consider the following example:
// Note that `responseBody` is not givenconstmockedGQLRequestWithSchema=mockRequest({requestPattern:/\/graphql/i,requestMethod:"POST",graphQLQueryName:"MyCoolQuery",graphQLAutoMocking:{// `schema` accepts a graphQL schema as string. An example:// https://github.com/trayio/mock-inspect/blob/main/src/tests/fixtures/simpleGraphQLSchemaString.tsschema:simpleGraphQLExampleSchemaString,},})// The response to this request will be automatically generated. It will look like:// { me: { name: "Drucill Hubert Lewse the Comer of Avera rejoices Fiann Craggy Florie and 5 hard trouts" }}constresponse=awaitexampleGraphQLPostRequestJson(` query MyCoolQuery { me { name } }`)
The propertygraphQLAutoMocking.fixedArrayLengths can be used to set a fixed array length or range for arrays that will be auto-generated. For this to work, we need to know of the type and the property in the formattype.property and the desired length/range.
Consider the below example: We are mocking a graphQL request that is expected to return ausers array.As we can see on the schema, theusers property sits underneath typeQuery. If we desire theusers array to be of length3, we would pass"Query.users": 3. If we desire it to be between the lengths 3 and 7, we would pass"Query.users": [3, 7].
constmockedGQLRequestWithSchema=mockRequest({requestPattern:/\/graphql/i,requestMethod:"POST",graphQLQueryName:"MyCoolQuery",graphQLAutoMocking:{schema:simpleGraphQLExampleSchemaString,fixedArrayLengths:{"Query.users":[3,7],},},})// The property `users` in this response will be of length between 3 and 7awaitexampleGraphQLPostRequestJson(` query MyCoolQuery { users { id, email, } }`)
Currently,jest provides no API to flush promises on its own. But flushing promises is necessary to have jest execute all built-up promises - and network responses are also promises. Therefore, you must flush the built-up promises manually. For this use case, we recommend usingthe async utilitywaitFor which is provided by the "Testing Library" project. Alternatively, you could create your own function which flushes a promise and call it as many times as needed:
exportconstflushPromises=async()=>{awaitnewPromise(setImmediate)}// Call `flushPromises` as many times as neededawaitflushPromises()
This library is based on themsw library.
Chameleon graphic byАнна Куликова fromPixabay
About
Mocks network requests and allows you to make assertions about how these requests happened. Supports auto-mocking of graphQL requests given a valid schema.
Topics
Resources
License
Code of conduct
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Contributors4
Uh oh!
There was an error while loading.Please reload this page.
