Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feat] update pact-js & msw versions #1742

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/sui-mock/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"main": "lib/index.js",
"description": "mock provider",
"types": "lib/index",
"type": "module",
"scripts": {
"lib": "babel --presets sui ./src --out-dir ./lib",
"prepublishOnly": "npm run lib",
Expand All @@ -17,7 +18,7 @@
"author": "",
"license": "MIT",
"dependencies": {
"msw": "0.47.4"
"msw": "2.2.8"
},
"repository": {
"type": "git",
Expand Down
15 changes: 10 additions & 5 deletions packages/sui-mock/src/browser.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
export {rest} from 'msw'
export {http as rest} from 'msw'

export const getBrowserMocker = async (handlers = []) => {
const setup = await import('msw').then(pkg => pkg.setupWorker)
const setup = await import('msw/browser').then(pkg => pkg.setupWorker)
const worker = setup(...handlers)

return {
...worker,
listen: worker.start,
close: worker.stop
close: worker.close,
listen: worker.listen,
printHandlers: worker.printHandlers,
resetHandlers: worker.resetHandlers,
restoreHandlers: worker.restoreHandlers,
start: worker.start,
stop: worker.stop,
use: worker.use
}
}
55 changes: 2 additions & 53 deletions packages/sui-mock/src/index.js
Original file line number Diff line number Diff line change
@@ -1,61 +1,10 @@
// /* global __MOCKS_API_PATH__ */
import {rest} from 'msw'
import {http} from 'msw'

import {getBrowserMocker} from './browser.js'
import {getServerMocker} from './server.js'

const isNode = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'

const setupMocker = isNode ? getServerMocker : getBrowserMocker

// TODO: Review error in Pipeline https://github.mpi-internal.com/scmspain/frontend-cf--web-app/actions/runs/3804318/job/12053812#step:5:238
// const generateHandlerFromContext = requester => {
// const handlers = requester
// .keys()
// .filter(path => path.startsWith('./'))
// .map(key => {
// const module = requester(key)
// return {
// path: key,
// ...(module.get && {get: module.get}),
// ...(module.post && {post: module.post}),
// ...(module.put && {put: module.put}),
// ...(module.del && {delete: module.del}),
// ...(module.patch && {patch: module.patch})
// }
// })
// .map(descriptor => {
// const {path, ...handlers} = descriptor
// const url = path.replace('./', 'https://').replace('/index.js', '')
// return Object.entries(handlers).map(([method, handler]) => {
// return rest[method](url, async (req, res, ctx) => {
// const body = ['POST', 'PATCH'].includes(req.method) ? await req.json() : '' // eslint-disable-line
// const [status, json] = await handler({
// headers: req.headers.all(),
// params: req.params,
// query: Object.fromEntries(req.url.searchParams),
// cookies: req.cookies,
// body
// })
// return res(ctx.status(status), ctx.json(json))
// })
// })
// })
// .flat(Infinity)
// return handlers
// }

// const setupMocker = legacyHandlers => {
// const mocker = isNode ? getServerMocker : getBrowserMocker
// const apiContextRequest = false
// // try {
// // apiContextRequest = require.context(__MOCKS_API_PATH__, true, /index\.js$/)
// // } catch (err) {
// // console.error(`[sui-mock] Not found route folder in ${__MOCKS_API_PATH__} autoload of msw handlers disabled`)
// // apiContextRequest = false
// // }
//
// return mocker([...legacyHandlers, ...(apiContextRequest && generateHandlerFromContext(apiContextRequest))])
// }

export {setupMocker, rest}
export {setupMocker, http as rest}
2 changes: 1 addition & 1 deletion packages/sui-mock/src/server.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export {rest} from 'msw'
export {http as rest} from 'msw'

export const getServerMocker = async (handlers = []) => {
const {setupServer} = require('msw/node')
Expand Down
25 changes: 16 additions & 9 deletions packages/sui-mock/test/common/indexSpec.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-env mocha */
import {expect} from 'chai'
import {rest} from 'msw'
import {http} from 'msw'

import {setupMocker} from '../../src/index.js'

Expand All @@ -15,14 +15,21 @@ describe('sui-mock | setupMocker', () => {

it('should init mocker with one handler', () => {
// Given
const handler = rest.get('/user/:userId', (req, res, ctx) => {
return res(
ctx.json({
firstName: 'John',
lastName: 'Maverick'
})
)
})
const handler = http.get(
'/user/:userId',
() =>
new Response(
JSON.stringify({
firstName: 'John',
lastName: 'Maverick'
}),
{
headers: {
'Content-Type': 'application/json'
}
}
)
)

// When
const mocker = setupMocker([handler])
Expand Down
15 changes: 13 additions & 2 deletions packages/sui-test-contract/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,24 @@
"test:server:watch": "npm run test:server -- --watch"
},
"dependencies": {
"@pact-foundation/pact": "9.18.1",
"@pactflow/pact-msw-adapter": "1.2.1",
"@pact-foundation/pact": "12.3.0",
"@pactflow/pact-msw-adapter": "3.0.0",
"@s-ui/mock": "1",
"commander": "8.3.0",
"headers-polyfill": "3.1.2"
},
"devDependencies": {
"@s-ui/domain": "2"
},
"config": {
"sui-test": {
"server": {
"esmOverride": true,
"useLibDir": false
}
}
},
"msw": {
"workerDirectory": "public"
}
}
2 changes: 2 additions & 0 deletions packages/sui-test-contract/src/setup/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,11 @@ const setupContractTests = ({
if (query) url = `${url}?${toQueryString(query)}`
try {
const {data} = body ? await fetcher[method](url, body, options) : await fetcher[method](url, options)

if (data) expect(data).to.deep.equal(response)
} catch (error) {
const data = error.response.data

if (data) expect(data).to.deep.equal(response)
}
})
Expand Down
4 changes: 2 additions & 2 deletions packages/sui-test-contract/src/setup/utils.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {stringify} from 'qs'

import {writeData2File} from '@pactflow/pact-msw-adapter/dist/utils/utils.js'
import {createWriter} from '@pactflow/pact-msw-adapter/dist/utils/utils.js'

const flatEntries = (input, prefix = '') =>
Object.entries(input).flatMap(([key, value]) => {
Expand Down Expand Up @@ -52,7 +52,7 @@ export const writerFactory = providers => (path, data) => {
})

console.log(`Writing the Pact file "${path}"`) // eslint-disable-line
writeData2File(path, data)
createWriter()(path, data)
}

export const mapProviders = providers =>
Expand Down
50 changes: 37 additions & 13 deletions packages/sui-test-contract/test/server/setupSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,16 @@ const gardenResponse = {
trees: [fujiAppleResponse, {color: 'green', type: 'Granny Smith'}]
}
const galaAppleBody = {color: 'red', type: 'Gala'}
const getAppleHandler = rest.get('http://localhost:8181/apples/:slug', (req, res, ctx) => {
const rotten = req.url.searchParams.get('rotten')
const response = rotten ? fujiRottenAppleResponse : fujiAppleResponse

return res(ctx.status(200), ctx.json(response))
const getAppleHandler = rest.get('http://localhost:8181/apples/:slug', ({request}) => {
const url = new URL(request.url)
const rotten = url.searchParams.get('rotten')
const json = rotten ? fujiRottenAppleResponse : fujiAppleResponse

return new Response(JSON.stringify(json), {
headers: {
'Content-Type': 'application/json'
}
})
})
const notFoundResponse = {code: 'not-found'}

Expand All @@ -38,8 +43,14 @@ setupContractTests({
endpoint: '/apples',
description: 'A request for getting some apples',
state: 'I have some apples',
handler: rest.get('http://localhost:8181/apples', (req, res, ctx) =>
res(ctx.status(200), ctx.json(applesResponse))
handler: rest.get(
'http://localhost:8181/apples',
() =>
new Response(JSON.stringify(applesResponse), {
headers: {
'Content-Type': 'application/json'
}
})
),
response: applesResponse
},
Expand All @@ -63,23 +74,29 @@ setupContractTests({
description: 'A request for adding a Gala apple',
state: "I've added a Gala apple",
method: 'post',
handler: rest.post('http://localhost:8181/apples/add/:slug', (req, res, ctx) => res(ctx.status(200))),
handler: rest.post('http://localhost:8181/apples/add/:slug', () => new Response()),
body: galaAppleBody
},
{
endpoint: '/apples/add/gala',
description: 'A request for adding a Gala apple with a different color',
state: "I've added a Gala apple with a different color",
method: 'post',
handler: rest.post('http://localhost:8181/apples/add/:slug', (req, res, ctx) => res(ctx.status(200))),
handler: rest.post('http://localhost:8181/apples/add/:slug', () => new Response()),
body: {color: 'yellow', type: 'Gala'}
},
{
endpoint: '/apples/garden',
description: 'A request for getting a garden',
state: 'I have a garden',
handler: rest.get('http://localhost:8181/apples/garden', (req, res, ctx) =>
res(ctx.status(200), ctx.json(gardenResponse))
handler: rest.get(
'http://localhost:8181/apples/garden',
() =>
new Response(JSON.stringify(gardenResponse), {
headers: {
'Content-Type': 'application/json'
}
})
),
response: gardenResponse,
addMatchingRules: true
Expand All @@ -88,8 +105,15 @@ setupContractTests({
endpoint: '/apples/search/garden',
description: 'A request for getting a garden that fails',
state: 'I have not garden',
handler: rest.get('http://localhost:8181/apples/search/garden', (req, res, ctx) =>
res(ctx.status(404), ctx.json(notFoundResponse))
handler: rest.get(
'http://localhost:8181/apples/search/garden',
() =>
new Response(JSON.stringify(notFoundResponse), {
status: 404,
headers: {
'Content-Type': 'application/json'
}
})
),
response: notFoundResponse
}
Expand Down
Loading