mswjs / msw

Industry standard API mocking for JavaScript.
https://mswjs.io
MIT License
15.95k stars 519 forks source link

MSW mock does not work in jest test #2013

Closed efeofluoglu closed 9 months ago

efeofluoglu commented 9 months ago

Prerequisites

Environment check

Browsers

No response

Reproduction repository

https://github.com/efeofluoglu/msw-mre

Reproduction steps

npm test

Current behavior

src/api/products/mocks contain the mocks (data and the response handler) for the use-my-products.test.ts

jest.config and jest.setup define the configuration for my test runner, jest. I define in jest.setup.js that jest should listen to my mswServer defined in src/api/msw-server

Here is the output from the test run:

- event [next-runtime-env] read environment variables prefixed with 'NEXT_PUBLIC_' from process.env.
- ready [next-runtime-env] wrote browser runtime environment variables to '/home/efe-bp/msw-mre/public/__ENV.js'.
  console.log
    undefined

      at log (src/apollo/config.js:49:19)

  console.log
    [Network error]: TypeError

      at log (src/apollo/config.js:51:17)

 FAIL  src/hooks/use-my-products.test.tsx
  useMyProducts
    ✕ should correctly return fetched products (1017 ms)

  ● useMyProducts › should correctly return fetched products

    expect(jest.fn()).toHaveBeenNthCalledWith(n, ...expected)

    n: 2
    Expected: {"loading": true, "myProducts": [{"description": "Description For Sample Product", "id": "product-id", "name": "Sample Product Name"}], "refetch": Any<Function>}
    Received
           1: {"loading": true, "myProducts": [], "refetch": [Function bound ]}
    ->     2
              Object {
            -   "loading": true,
            -   "myProducts": Array [
            -     Object {
            -       "description": "Description For Sample Product",
            -       "id": "product-id",
            -       "name": "Sample Product Name",
            -     },
            -   ],
            -   "refetch": Any<Function>,
            +   "loading": false,
            +   "myProducts": Array [],
            +   "refetch": [Function bound ],
              },

    Number of calls: 2

    Ignored nodes: comments, script, style
    <html>
      <head />
      <body>
        <div>
          <div>
            hello world
          </div>
        </div>
      </body>
    </html>

      43 |         refetch: expect.any(Function),
      44 |       });
    > 45 |       expect(spy).toHaveBeenNthCalledWith(2, {
         |                   ^
      46 |         myProducts: expectedProducts,
      47 |         loading: true,
      48 |         refetch: expect.any(Function),

      at toHaveBeenNthCalledWith (src/hooks/use-my-products.test.tsx:45:19)
      at runWithExpensiveErrorDiagnosticsDisabled (node_modules/@testing-library/dom/dist/config.js:47:12)
      at checkCallback (node_modules/@testing-library/dom/dist/wait-for.js:124:77)
      at checkRealTimersCallback (node_modules/@testing-library/dom/dist/wait-for.js:118:16)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        1.66 s, estimated 2 s
Ran all test suites.

The test fails because the expected responses dont match. The received response contains an empty array for myProducts even though I've specified the response data in src/api/products/mocks

Expected behavior

The response data in test should have myProducts filled with the data that the handler uses

kettanaito commented 9 months ago

Hi, @efeofluoglu. Thanks for reporting this.

Following your reproduction steps results in this error when I run npm test:

> msw-mre@0.1.0 test
> TZ=UTC jest --all --watchAll=false --testResultsProcessor=jest-junit --coverage

- event [next-runtime-env] read environment variables prefixed with 'NEXT_PUBLIC_' from process.env.
- ready [next-runtime-env] wrote browser runtime environment variables to '/msw-2013/public/__ENV.js'.
Error: > Couldn't find any `pages` or `app` directory. Please create one under the project root
    at findPagesDir (/msw-2013/node_modules/next/dist/lib/find-pages-dir.js:42:15)
    at /msw-2013/node_modules/next/dist/build/jest/jest.js:116:75
    at async readConfigFileAndSetRootDir (/msw-2013/node_modules/jest-config/build/readConfigFileAndSetRootDir.js:129:20)
    at async readInitialOptions (/msw-2013/node_modules/jest-config/build/index.js:403:13)
    at async readConfig (/msw-2013/node_modules/jest-config/build/index.js:147:48)
    at async readConfigs (/msw-2013/node_modules/jest-config/build/index.js:424:26)
    at async runCLI (/msw-2013/node_modules/@jest/core/build/cli/index.js:151:59)
    at async Object.run (/msw-2013/node_modules/jest-cli/build/run.js:130:37)

Could you please resolve it and let me know? Thanks.