Comments (15)
As MSW will eventually support mocking in non-browser environments, I think that such initializer functions like composeMocks()
should clearly describe what are they initializing.
I suggest the following API:
useWorker()
function useWorker(...handlers: RequestHandler[]): WorkerAPI
Uses a Service Worker with the given request handlers.
useServer()
function useServer(...handlers: RequestHandler[]): unknown
Stubs an XHR communication with the given request handlers, thus, mimicking a server.
I'm not found of a word "server" where there are no actual servers, so please feel free to share what name makes more sense to you.
from msw.
// Browser usage
import { setupServiceWorker } from 'msw'
const { start, stop } = setupServiceWorker(options)
start()
// Node usage
import { setupMockServer } from 'msw'
setupMockServer(options)
from msw.
Hi @kettanaito,
Definitely, composeMocks
is not aligned with what it actually does at the end, and compose
is quite generic keywords and agree with you that many libraries already have implemented it.
Although, composeHandlers
sounder better option that what we already have, however if you ask me I would suggest to look for something which doesn't include compose
word at all.
These are a few of them I can think about at the moment:
responseEngine
because we are takingrequests
and giving youresponse
if youstart()
the engine. You wont get theresponse
if youstop()
the engine.responseFactory
ifresponseEngine
sounds too fancy.workerEngine
because under the hood its service worker doing all things.responseHandler
because we are takingrequests
as it is but controllingresponse
- Or maybe any permutation combination of above mention items.
What do you think @hehehai ?
from msw.
@hehehai, @redraushan, as valuable contributors, what is your opinion on this API change? What consequences do you see this introducing?
from msw.
Dropping the compose
part may be a good idea. I'll try to brainstorm of the names below.
createSchema()
withMocks()
addMocks()
from msw.
@kettanaito, anything finalised if we are keeping composeMocks
name as it is?
from msw.
I do love how addMocks()
reads and sounds, been thinking of it these two days. I find it crucial we also consider this function in isolation (i.e. close to a React component it's associated with). The name should make sense in that case also.
from msw.
@kettanaito addMocks
sounds readable however the only thing which is off is the parameter of addMocks
are request handlers, but maybe request handlers can be also considered as mocks. I don't know I am pretty bad at naming things :D
from msw.
‘useWorker()’ and ‘useServer()’ sounds clean to me, I think we can move forward with this.
from msw.
in React ‘use’ is the prefix for React hooks. I propose we use the name ‘run’.
runMockServiceWorker
runMockServer
from msw.
@andreawyss, you're right about the hook prefix. We've had an internal discussion, and that React convention has came up as well.
I like how run
can partially replace use
in meaning, but in regards to Mock Service Worker functionality, I think it's a little confusing to call runMockWorker()
when that function doesn't actually run the worker. The start()
function does (so you have granular control over when to start or stop the worker).
I believe such API is misleading:
import { runMockWorker } from 'msw'
// Now I expect that the worker runs after I call this function,
// but in reality it's not.
const { start, stop } = runMockWorker(...)
start()
Perhaps, there's a closer replacement to use
in semantical meaning?
from msw.
@andreawyss, that looks lovely!
What do you think if we drop the "Service" part, and it becomes:
// Browser usage
setupMockWorker()
// Node usage
setupMockServer()
I'm also thinking that perhaps it would be a good idea to delegate "starting" the mocked server to the usage surface. That is mainly for two reasons:
- Resolving a mock response is an async action. That allows you to dispatch side-effects (such as
ctx.fetch()
to fetch original response), but also means they need to be awaited before returned as response.
This makes the request handler itself asynchronous.
- Since attaching a mock server is a side-effect on its own, I think it's common to give control over when it starts and ends in your test suite (
beforeAll
,afterAll
, etc.).
import { setupMockServer } from 'msw'
import handlers from '../shared/handlers'
describe('Test', () => {
beforeAll(async () => {
const mock = setupMockServer(handlers)
// Or whichever method that's suitable in the context
await mock.open()
})
afterAll(async () => {
await mock.close()
})
})
from msw.
Great. I like the symmetry of the setup function names.
Also the default response latency (delay) would be about 700 ms for the mock worker and about 5ms for the mock server.
These values can be changed in the options passed to the setup functions.
const mockWorker = setupMockWorker({ handlers, latency: 1000 })
const mockServer = setupMockServer({ handlers, latency: 60 })
Using an option object will allow in the future to add new options as needed.
from msw.
@andreawyss, agree on the options object. Actually, version 0.14.0
already ships with the options to start()
being an object, so you can opt-out from logging, for example. Global delay (latency) may also be a viable thing to configure.
from msw.
Thank you everybody for this discussion! I've decided to go with the following options:
setupWorker()
setupServer()
I'm omitting the "mock" part taking in consideration that you import those functions from a library that does mocking already, and it should be a pre-requisite in understanding.
from msw.
Related Issues (20)
- Add delay before each request HOT 3
- Mock a request that contains both query and path parameters
- TypeError: confirm is not a function HOT 7
- Failing to intercept an Axios request: Node 20.11 + Vitest 1.3.1 + MSW 2.2.1
- v2.2.2 does not intercept request in browser mode (CORS error) but v1.3.1 does HOT 3
- Infering the `boundary` callback arguments HOT 7
- support custom fetch option HOT 7
- support selecting interceptors HOT 1
- Set-Cookie responses containing commas are not handled correctly HOT 1
- HttpResponse.json() throwing TypeError: Right-hand side of 'instanceof' is not an object. HOT 1
- Request with FormData body makes Jest hang forever HOT 6
- TypeError: Right-hand side of 'instanceof' is not an object HOT 4
- Cannot read properties of undefined (reading 'url') HOT 5
- Mocked data getting empty string HOT 8
- "InvalidStateError: The object is in invalid state" when mocking rest api
- Unable to use msw/node for testing solid-js due to `resolve.conditions` set to `browser` HOT 5
- drop CommonJS support HOT 2
- quiet: true should supress RESPONSE LISTENER logs HOT 4
- Narrowing the response body type in `HttpResponse.json` HOT 16
- Error: No known conditions for "./browser" specifier in "msw" package HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from msw.