question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Mock response is overwritten with {}

See original GitHub issue

Environment

Name Version
msw 0.36.4
node v16.13.0
OS MAC 12.0.1

Request handlers

setup:
// Establish API mocking before all tests.
beforeAll(() => server.listen({
    onUnhandledRequest: 'warn',
  }))
// Reset any request handlers that we may add during the tests,
// so they don't affect other tests.
afterEach(() => {
	server.resetHandlers();
  
  // This is the solution to clear RTK Query cache after each test
	store.dispatch(orchestrator.util.resetApiState());
});
// Clean up after the tests are finished.
afterAll(() => server.close())

handler:
import { rest } from 'msw'

export const handlers = [
    rest.post('http://localhost/cash-advance/validate', (req, res, ctx) => {
        return res(
            ctx.status(200),
            ctx.json({"linkId":"123","validationState":"VALID_CUSTOMER","customer":{}}),
        )
    })
  ];
  
  

Actual request

I am using RTK Query

// Example of making a request. Provide your code here.
  const {
    data,
    isError,
    error,
    refetch: refetchPostInitialize,
  } = usePostValidateQuery(linkId, {
    skip: linkId == null || idToken === '',
  });
Here is the createAPI:
export const orchestrator = createApi({
  reducerPath: 'orchestrator',
  baseQuery,
  endpoints: (builder) => ({
    postValidate: builder.query({
      query: (linkId: string | undefined) => ({
        url: `cash-advance/validate?linkId=${linkId}`,
        method: 'POST',
      }),
    }),

Current behavior

When I run the test it appears to return nothing. when I run the test using the debug package with DEBUG=* I see the following:

  XHR POST cash-advance/validate?linkId=link_id received mocked response {
  status: 200,
  statusText: 'OK',
  headers: { 'x-powered-by': 'msw', 'content-type': 'application/json' },
  body: '{"linkId":"123","validationState":"VALID_CUSTOMER","customer":{}}'
} +149ms
  XHR POST cash-advance/validate?linkId=link_id trigger "loadstart" (1) +0ms
  XHR POST cash-advance/validate?linkId=link_id resolve listener for event "loadstart" +0ms
  XHR POST cash-advance/validate?linkId=link_id set response status 200 OK +0ms
  XHR POST cash-advance/validate?linkId=link_id set response headers HeadersPolyfill {
  _headers: { 'x-powered-by': 'msw', 'content-type': 'application/json' },
  _names: Map(2) {
    'x-powered-by' => 'x-powered-by',
    'content-type' => 'content-type'
  }
} +0ms
  XHR POST cash-advance/validate?linkId=link_id readyState change 1 -> 2 +0ms
  XHR POST cash-advance/validate?linkId=link_id triggerring readystate change... +0ms
  XHR POST cash-advance/validate?linkId=link_id trigger "readystatechange" (2) +0ms
  XHR POST cash-advance/validate?linkId=link_id resolve listener for event "readystatechange" +0ms
  XHR POST cash-advance/validate?linkId=link_id response type blob +1ms
  XHR POST cash-advance/validate?linkId=link_id coerced response body to {"linkId":"123","validationState":"VALID_CUSTOMER","customer":{}} +0ms
  XHR POST cash-advance/validate?linkId=link_id get response header "content-type" +0ms
  XHR POST cash-advance/validate?linkId=link_id resolved response header "content-type" to "application/json" HeadersPolyfill {
  _headers: { 'x-powered-by': 'msw', 'content-type': 'application/json' },
  _names: Map(2) {
    'x-powered-by' => 'x-powered-by',
    'content-type' => 'content-type'
  }
} +0ms
  XHR POST cash-advance/validate?linkId=link_id resolving response body as Blob { type: 'application/json' } +0ms
  XHR POST cash-advance/validate?linkId=link_id get response header "Content-Type" +0ms
  XHR POST cash-advance/validate?linkId=link_id resolved response header "Content-Type" to "application/json" HeadersPolyfill {
  _headers: { 'x-powered-by': 'msw', 'content-type': 'application/json' },
  _names: Map(2) {
    'x-powered-by' => 'x-powered-by',
    'content-type' => 'content-type'
  }
} +1ms
  XHR POST cash-advance/validate?linkId=link_id set response body Blob {} +0ms
  XHR POST cash-advance/validate?linkId=link_id readyState change 2 -> 3 +0ms
  XHR POST cash-advance/validate?linkId=link_id triggerring readystate change... +0ms
  XHR POST cash-advance/validate?linkId=link_id trigger "readystatechange" (3) +0ms
  XHR POST cash-advance/validate?linkId=link_id resolve listener for event "readystatechange" +0ms
  XHR POST cash-advance/validate?linkId=link_id trigger "progress" (3) +0ms
  XHR POST cash-advance/validate?linkId=link_id resolve listener for event "progress" +0ms
  XHR POST cash-advance/validate?linkId=link_id readyState change 3 -> 4 +0ms
  XHR POST cash-advance/validate?linkId=link_id triggerring readystate change... +0ms
  XHR POST cash-advance/validate?linkId=link_id trigger "readystatechange" (4) +0ms
  XHR POST cash-advance/validate?linkId=link_id resolve listener for event "readystatechange" +0ms
  XHR POST cash-advance/validate?linkId=link_id trigger "load" (4) +0ms
  XHR POST cash-advance/validate?linkId=link_id resolve listener for event "load" +0ms
  XHR POST cash-advance/validate?linkId=link_id get all response headers +1ms
  XHR POST cash-advance/validate?linkId=link_id trigger "loadend" (4) +0ms
  XHR POST cash-advance/validate?linkId=link_id resolve listener for event "loadend" +0ms

At the beginning I see the mock response. Then further down I see “response type blob” then “set response body Blob {}”. The UI gets nothing in the data variable. It is undefined which would correspond to the api returning {}.

Expected behavior

I expect the data variable to get

{"linkId":"123","validationState":"VALID_CUSTOMER","customer":{}}

Screenshots

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
kettanaitocommented, Jun 22, 2022

@edwinvrgs, we’re mentioning the request integrity with the GraphQL client here. It may not be obvious at first but you need to compose the same response in regards to what the client expects. In the case of Apollo, all fields must have __typename. Apollo will strip off any fields that don’t. This is a behavior not specific to MSW in any way.

2reactions
edwinvrgscommented, Jun 22, 2022

Fixed by using __typename.

  ctx.data({
    currentUser: {
      __typename: "User",
      ...user
    },
  }),
Read more comments on GitHub >

github_iconTop Results From Across the Web

How to overwrite the mocked data for a module in different ...
I have a scenario where I have to update the mocked response for a module with different set of values in a different...
Read more >
Overwriting Mocks in Jasmine - Bambielli's Blog
TIL how to overwrite mocks in tests, by saving them to a variable and modifying the function tied to the object.
Read more >
respond - mock
Always respond with same overwrite.
Read more >
Can we overwrite mocked values returned in LWC Jest?
I thought it should theoretically by possible to mock a custom label differently on a per-test basis. I explored some options involving jest ......
Read more >
Jest Mocking Strategies | Mercedes Bernard
Recently, I've been spending more time wrestling with uncooperative mocks than writing the code or the tests combined. I created this post to ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found