Can't see to find any good docs on how to mock/stub the server Sider side requests with playwright.
An example would be to intercept the getServerSideProps in nextjs: hitting the routes makes the server do a request (db API etc). Then it can do some business logic (which should also be covered by testing) before it is passed to the component as props which is sent to the client (being server side rendered).
Mocking that db API request without having some test logic mixed into the business logic is what I am hoping to find an answer for.
Playwright allows you to do interception and mocking/stubbing.
UI action can triger the API call, and without sending request you can intercept
the response.
And you can use moks and stubs as well.
const mock = { animals: [] }
await page.route('**/Zoo/v1/books', (animals) =>
route.fulfill({
status: 304,
body: JSON.stringify(mock),
})),
);
await page.goto('https://www.demoqa/animals');
See more https://github.com/microsoft/playwright/issues/1774#issuecomment-769247500
And https://playwright.dev/docs/next/network#modify-responses
Related
My front-end is built with vue, and the back-end is with golang. My questions are 1. When I click the button to request a third-party login, how do I judge that the third-party authentication is successful? 2. And how do I get the data on the server side
The second question I think of is to save data on the server side through cookies and session, and the front end can get information through the cookie HTTP request header. Is there a more concise way
The second question, how can I judge the success of the third-party authentication?
My jump Url code is
/// vuex
async accountLoginAction({ commit, dispatch }, payload: any) {
const from: string = payload
window.location.href = getMixinUrl(from)
},
Through this code, the page can be jumped to a third party, then how can I judge that the authentication is successful? And how to request data gracefully when the judgment is successful.
I have an endpoint written in expressjs
router.post("/mkBet", async (req, res) => {
console.log(req.body)
const betToPush = new Bet({
addr: req.body.address,
betAmount: req.body.amount,
outcome: req.body.didWin,
timePlaced: Math.round(+new Date()/1000)
})
try {
const newBet = await betToPush.save()
res.status(201).json(newBet)
} catch(err) {
res.status(400).json({message: err.message})
}})
And I am trying to make it so that it can only be called when an action is performed on the frontend. So users cannot call it with custom arguments to make it so the outcome is always true. What would be the best way to achieve this?
It is not possible to securely tell what client sent the request. In other words, a request from your client and a different one can be identical in general.
Talking about unmodified browsers (as opposed to non-browser tools like Postman), you can tell the origin of the request (~the url loaded in the browser when the request was sent) with some confidence from the Origin and Referer request headers. However, your backend needs authentication and authorization anyway.
With the latter two in place, ie. with proper security implemented on the server-side, it doesn't matter anymore what client sends the requests.
My request url has multiple query params. I want to mock the response of the external API while writing my tests in Testcafe. I want to mock the data in E2E testing because my data will expire in every 15days.
Please suggest some ways to handle mocking the request with query param. I am able to mock the request not having any query param and I am using Request Hooks for that.
There shouldn't be a difference between a mocking response from URL with parameters and without them. You can mock a response by using RequestMock API:
...
const getDataMock = RequestMock()
.onRequestTo(/.*getData\?param=param_1/)
.respond((req, res) => {
res.setBody({...});
});
...
If this doesn't work for you, please provide us with the code where you define RequestMock or RequestHook.
I have a SPA application that talks with API that deployed on another server. For example, when I click a Submit button it sends XHR request to it API, and I need to wait for a response to check it. How can I do this?
Put this in cypress/support/commands.js:
Cypress.Commands.add('manageMyApiRequests', () => {
cy.route('/URL/Of/api/I/Want/To/wait/For').as('myApi')
});
Then in your test or before each call:
cy.server();
cy.manageMyApiRequests();
Then where-ever you want to wait for that api response just do:
cy.wait('#myApi');
The same can also be acheived without the first cypress command manageMyApiRequests but I suggest you use this for better organization of your tests and then later you can also add more apis to the same function.
FYI you can also use .then() it if you want to check something within the response:
cy.wait('#myApi').then((xhr) => {
// we can now access the low level xhr
// that contains the request body,
// response body, status, etc
});
I have a React App that uses React Router and Redux as its state manager. The server side of the app uses Express and Node.
I am making API calls to an external service. I do not have the ability to enable CORS on the external service. Therefore, I need to use my app's server side to make the calls to the external service to remove the browser from the equation, and eliminate any CORS error.
I am able to get my data from the service on the server side successfully. I would like to know if it is possible to share the Redux store in between the client and server with some sort of middleware (looking for examples/resources).
The goal:
1) Handle a click event in the client
2) Have that event call a server side route to external api (don't know how to do this)
3) Then the server handles this route, makes the request, and sends the response to the client (through the shared react store - not sure if this is possible)
4) The store gets the new state, and then sends to the client side components, and the UI updates
Are there any examples/tutorials of this? Not looking for an initial server rendered page, but guides that inform how the above 4 steps can generally be implemented.
Thanks for the suggestions.
It turns out that I was severely over thinking the solution. All I really needed was the ability to launch a server side function (get resources from external API) from the client side event (load component). Sort of like how submitting a form, has an action that launches a server side function.
In my component:
componentDidMount() {
const product_api_results = productApi.getProductItems()
console.log('product_api_results in CART Component: ', product_api_results)
/* now I have results and can put it in the Redux Store via action to reducer for other components to work with on client */
}
The productAPI.getProductItems() that the component calls:
export function getProductItems () {
return axios.get('/api/get-products') // triggers a server side route
.then(function (response) {
console.log('client side response: ', response)
return response
})
}
In Express server.js file, the server will see this url and then get the proper data. The shopify.get() is from the shopify-node-api module:
app.get('/api/get-products', function (req, res) { // '/api/get-products' called from client
shopify.get('/admin/products.json', function (err, data, headers) {
res.send(data)
})
})