vitest + msw / testing reactQuery (axios) hooks using renderHook / unable to avoid error logging from test suite - react-query

Using a custom logger as follow for our test suite :
export const queryClient = new QueryClient({
logger: {
log: console.log,
warn: console.warn,
error: () => {}
}
});
Mocking errors as follow within msw :
rest.get('/some/api/route', (_req, res, ctx) => {
return res.once(ctx.status(500), ctx.json({ errorMessage: 'some error' }));
})
We override the handlers for errors :
it("should return error", () => {
server.use(...errorHandlers);
const { result } = renderHook(() =>
query({
url: '/some/api/routes',
options: { retry: false }
})
);
...some assertions
});
Out tests are ok, but the network errors are still appearing in the console when running the test suite (the display is thrashed) :
Error: Request failed with status code 500
at createError (.../node_modules/axios/lib/core/createError.js:16:15)
at settle (.../node_modules/axios/lib/core/settle.js:17:12)
at XMLHttpRequestOverride.onloadend (.../node_modules/axios/lib/ad
... super long logging ...
Such non blocking issue is tackled in other projects using jest as the custom queryClient logger does the job; it seems that it behaves differently using vitest. Does anyone knows which part is the culprit in that context ? What should be done ?

passing a custom logger to the QueryClient is a feature that was introduced in v4.
For v3, you need to call setLogger, which is exported from react-query:
https://react-query-v3.tanstack.com/reference/setLogger
import { setLogger } from 'react-query'
setLogger({
log: console.log,
warn: console.warn,
error: () => {}
})

Related

error in depolying contract >> Error: could not detect network (event="noNetwork", code=NETWORK_ERROR, version=providers/5.7.2)

im trying the depoy my contract using npx hardhat run scripts/deploy.js --network goerli and i keep geeting the above error
//this is the error
omota#DESKTOP-3T9OR5N MINGW32 ~/web3-projects/tinder-blockchain/smart-contract (main)
$ npx hardhat run scripts/deploy.js --network goerli
Compiled 1 Solidity file successfully
error in depolying contract >> Error: could not detect network (event="noNetwork", code=NETWORK_ERROR, version=providers/5.7.2)
at Logger.makeError (C:\Users\omota\web3-projects\tinder-blockchain\smart-contract\node_modules\#ethersproject\logger\src.ts\index.ts:269:28)
at Logger.throwError (C:\Users\omota\web3-projects\tinder-blockchain\smart-contract\node_modules\#ethersproject\logger\src.ts\index.ts:281:20)
at EthersProviderWrapper.<anonymous> (C:\Users\omota\web3-projects\tinder-blockchain\smart-contract\node_modules\#ethersproject\providers\src.ts\json-rpc-provider.ts:483:23)
at step (C:\Users\omota\web3-projects\tinder-blockchain\smart-contract\node_modules\#ethersproject\providers\lib\json-rpc-provider.js:48:23)
at Object.throw (C:\Users\omota\web3-projects\tinder-blockchain\smart-contract\node_modules\#ethersproject\providers\lib\json-rpc-provider.js:29:53)
at rejected (C:\Users\omota\web3-projects\tinder-blockchain\smart-contract\node_modules\#ethersproject\providers\lib\json-rpc-provider.js:21:65)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
reason: 'could not detect network',
code: 'NETWORK_ERROR',
event: 'noNetwork'
}
//here is my depoy.js file
const { ethers } = require('hardhat')
const main = async () => {
const tinderFactory = await ethers.getContractFactory('TinderERC721')
const tinderContract = await tinderFactory.deploy()
console.log('TINDER CONTRACT ADDRESS:', tinderContract.address)
};
main()
.then(() => process.exit(0))
.catch(error => {
console.log('error in depolying contract >>', error);
process.exit(1);
})
//here is my hardhat-config.js
require("#nomicfoundation/hardhat-toolbox");
require('dotenv').config({path: '.env'})
const ALCHEMY_API_URL = process.env.ALCHEMY_API_URL
const GOERLI_PRIVATE_KEY = process.env.GOERLI_PRIVATE_KEY
/** #type import('hardhat/config').HardhatUserConfig */
module.exports = {
defaultNetwork: 'goerli',
networks: {
goerli: {
url: ALCHEMY_API_URL,
accounts: [`0x${GOERLI_PRIVATE_KEY}`],
},
},
solidity: '0.8.17',
}
any help will be appreciated
i have done anything i can but still the same
I had the same error. Since you are using .env to store the private keys, if the value is being stored as:
"https://eth-goerli.alchemyapi.io/v2/${ALCHEMY_API_KEY}" within the .env file itself, change it to the full link instead:
"https://eth-goerli.alchemyapi.io/v2/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
I was also getting a "private key too long" error as well because of using semi-colons to separate statements within the .env file... Hope this helps!
Maybe you have some problems with the ALCHEMY_API_URL. It should be in the form:
https://eth-goerli.alchemyapi.io/v2/${ALCHEMY_API_KEY}
Or for sure, you can use public RPC nodes:
https://goerli.infura.io/v3/ //default on metamask
https://rpc.ankr.com/eth_goerli //I tried and it worked
https://eth-goerli.public.blastapi.io
https://rpc.goerli.mudit.blog

While testing error responses, the test fails with the expected error (React/Jest/ReactQuery/Axios/MSW)

I am trying to test error states of the following MSW rest endpoint:
import { rest } from 'msw'
export const exceptionHandlers = [
rest.post(config.accountApiUrl + '/login', (req, res, ctx) => {
return res(
ctx.status(500),
ctx.json({ data: { message: 'Mock Error Message' } })
)
})
]
This endpoint is called in a custom hook return function thats using React Query's mutateAsync:
const { mutateAsync } = useMutation(AuthApi.login)
const handleLogin = async (props): Promise<void> => {
await mutateAsync(props, {
onSuccess: async () => {
// this block tests fine
}
onError: async () => {
console.log('!!!')
// it reaches this block, '!!!' is logged to the console,
// but the test still fails with `Request failed with status code 500`
}
})
}
return handleLogin
In a test file:
it('handles network errors', async () => {
mswServer.use(...exceptionHandlers)
const user = userEvent.setup()
const screen = render(<LoginForm />)
const submitButton = screen.getByTestId('Login.Submit')
// Complete form
await user.click(submitButton)
})
It doesnt matter what comes after that, the test always fails with
Request failed with status code 500
at createError (node_modules/axios/lib/core/createError.js:16:15)
at settle (node_modules/axios/lib/core/settle.js:17:12)
at XMLHttpRequestOverride.onloadend (node_modules/axios/lib/adapters/xhr.js:54:7)
at XMLHttpRequestOverride.trigger (node_modules/#mswjs/interceptors/src/interceptors/XMLHttpRequest/XMLHttpRequestOverride.ts:176:17)
at node_modules/#mswjs/interceptors/src/interceptors/XMLHttpRequest/XMLHttpRequestOverride.ts:354:16
But its supposed to fail with status 500. That's the whole point. If I change the handler to return another error, ie ctx.status(404), then the test just fails with that error code.
I've tried wrapping the assertion in a try/catch block but the same thing results. I see examples online of people doing (apparently) exactly this and it works fine, so I'm quite confused what's causing this. All other tests that check success states work as expected.
i've had the same problem.
As far as i could understand, the problem is that in test environment there is no handler for the rejected promise.
https://github.com/TanStack/query/issues/4109

Exceeded timeout of 5000 ms for a test with Jest and MongoDB

I'm trying to implement database population by using a migration function. The code works perfectly, it saves all the data into the database, but the test for the function is failing, and now I would like to know why?
I'm getting the "Exceeded timeout of 5000 ms" error for this particular test. I've written 166 tests for this app and all of them are passing.
Here is the function I want to test:
const doMigration = async ({ model, data }) => {
await model.collection.insertMany(data)
}
And here is the test:
const { Amodel } = require('../../../models/Amodel')
const { doMigration } = require('../../../database/migrations')
describe('Database Population', () => {
it ('Should populate the database using migrations', async () => {
const data = [{ name: 'A' }, { name: 'B' }]
const model = Amodel
const migration = { name: 'Amodel', model, data }
await doMigration(migration)
const countAfter = await Amodel.count()
expect(countAfter).toBe(2)
})
})
In this test I simply import the function, the model and create a migration object that then is passed to the function.
What did I try?
Tried using just the countAfter without using the doMigration function, and it still generates the same timeout error.
Tried increasing the time for this test to 30000, failed with error saying that the mongodb time exceeded the 10000 ms.
Here is the github repository: https://github.com/Elvissamir/Fullrvmovies
What is happening, how can I solve this error?
The problem was the way the mongodb connection was handled. When testing, the app created a connection to the db on startup, and then the jest tests used that connection, that caused some issues.
The solution was to connect to the database on startup only if the environment is set to testing, otherwise the connection will be handled by each set of tests.
In each set I added a beforeAll and afterAll to open and close the connection to the database.
Hope it helps anyone that finds the same problem or has similar issues.
The orientation is that the message reflect the actual reason, So i recommand to follow the following steps:
use the following code to check mongo state:
const { MongoMemoryServer } = require("mongodb-memory-server");
const mongoose = require("mongoose");
(async () => {
mongod = await MongoMemoryServer.create();
const mongoUri = mongod.getUri();
await mongoose.connect(mongoUri, {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then((result) => {
console.log(result.connection.readyState)
console.log(result.connection.host)
}).catch((err) => {
});;
})();
if you are using mongodb-memory-server add "testTimeout" attribute:
"jest": {
"preset": "ts-jest",
"testEnvironment": "node",
"setupFilesAfterEnv": [
"./src/test/setup.ts"
],
"testTimeout": 15000
},
If all above still huppens check the time-out of all inter-test operation

axios / jest - unabled to perform a call request (TypeError: Cannot read property 'then' of undefined)

I'm struggling to perform a test with jest concerning an axios api call
here is my API call, that works perfectly within my program
import axios from 'axios';
import crypto from 'crypto';
import { prop } from 'ramda';
const baseUrl = 'http://gateway.marvel.com:80';
const uri = '/v1/public/characters';
const charactersUrl = baseUrl + uri;
const timestamp = [Math.round(+new Date() / 1000)];
const privateApi = 'XXX';
const publicApi = 'XXX';
const concatenatedString = timestamp.concat(privateApi, publicApi).join('');
const hash = crypto.createHash('md5').update(`${concatenatedString}`).digest('hex');
const charactersApi = () =>
axios
.get(charactersUrl, {
params: {
ts: timestamp,
apikey: publicApi,
hash,
},
})
.then(prop('data'));
export default charactersApi;
When I'm trying to test it, that way:
import axiosMock from 'axios';
import charactersApi from '../marvelApi';
jest.mock('axios', () => ({
get: jest.fn(),
}));
describe('tools | marvelApi', () => {
const piece = { name: '3D-MAN' };
axiosMock.get.mockResolvedValueOnce({ data: piece });
it('should get the character', () => {
return charactersApi().then(elem => {
expect(elem.name).toEqual('3D-MAN');
});
});
});
I get the following message from jest
TypeError: Cannot read property 'then' of undefined
16 |
17 | const charactersApi = () =>
> 18 | axios
| ^
19 | .get(charactersUrl, {
20 | params: {
21 | ts: timestamp,
at charactersApi (src/tools/marvelApi.js:18:3)
at Object.<anonymous> (src/tools/tests/marvelApi.test.js:13:12)
What I have tried
A common error is to forget the return statement within the function that contain the request API, in my case it's done correctly (first piece of code -> charactersApi()) source1, source2
I also tried to return a Promise from the mocked Axios as I have seen on another SO ticket
jest.mock('axios', () => ({
get: jest.fn(() => Promise.resolve()),
}));
I think my axios mock is not correct, because the struggle comes from the test while the production version work well
Any thoughts ?
You can spy on the "axios.get" calls and resolve them to a fixed (mocked) value:
/**
* #jest-environment jsdom
*/
const axios = require('axios')
beforeAll(() => {
jest.spyOn(axios, 'get').mockImplementation()
})
afterAll(() => {
jest.restoreAllMocks()
})
it('returns the mocked response', async () => {
axios.get.mockResolvedValue({ data: 'foo' })
const res = await axios.get('https://api.github.com')
expect(res).toEqual({ data: 'foo' })
})
You shouldn't use jest.mock because it mocks a module that your imported code may be using. As far as I know, it doesn't affect the current module's imports (and you import axios as a part of your test).
Recommended solution
I strongly discourage you from spying/mocking axios directly. See my argumentation below.
You're mocking implementation details of axios. In other words, you take the axios.get function and throw it away, alongside any internal logic it may have, and replace it with a hard mock. This means your test no longer uses axios, instead it uses an emptied mocked shell of axios. This makes your test different from your actual code, which, in turn, decreases the confidence such a test gives you.
You're coupling your mocks with a specific request client (axios). Such an approach is not a long-term investment, as you're writing axios-specific mocks. You can't reuse such mocks for requests made by other clients (i.e. window.fetch, Apollo, etc.), because they have their own implementation details (i.e. window.fetch has no .get() to spy on), which only encourages you to write more implementation-specific logic in tests.
You can learn more about the disadvantages of direct mocking of request clients in the Stop mocking fetch article by Kent C. Dodds. It uses window.fetch mocks as an example, but you may replace it with ANY_REQUEST_CLIENT when reading.
I highly recommend using tools like Mock Service Worker (MSW) that will encourage you to write abstracted mocks that don't rely on any request clients (you can use them no matter how your tested code makes a request) and can even be reused across different testing levels (the same mocks for Jest, Storybook, or Cypress).
Here's how your test would look like with MSW:
import { rest } from 'msw'
import { setupServer } from 'msw/node'
import charactersApi from '../marvelApi';
const server = setupServer(
rest.get('http://gateway.marvel.com:80/v1/public/characters', (req, res, ctx) => {
return res(ctx.json({
data: {
name: '3D-MAN'
}
}))
})
)
beforeAll(() => server.listen()
afterAll(() => server.close())
describe('tools | marvelApi', () => {
it('should get the character', () => {
return charactersApi().then(elem => {
expect(elem.name).toEqual('3D-MAN')
})
})
})
Notice how there are no details about how the request is made, only which request to intercept and mock its response.
You can follow a detailed tutorial on how to Get started with MSW. There's also a great video on API mocking and what problems MSW solves.

sails helpers and machine spec

I upgrade sails to the #^1.0.0 version and while I'm developing an API, I wanted to use a Service but the Sails document advice to use Helper now. And I don't realy use to work with the new way to discripe helper, build script or actions.
And all the try I have mad wasn't successful.
In the following exemple..
Here is my controller call:
var ob = await ails.helpers.testy('sayHello');
res.json({ob:ob});
helper
module.exports = {
friendlyName: 'Testy',
description: 'Testy something.',
inputs: {
bla: {
type: 'string'
}
},
exits: {
success: {
}
},
fn: async function (inputs, exits) {
console.log({blabla:inputs.bla})
if(!inputs.bla) return exits.error(new Error('text not found'));
var h = "Hello "+ inputs.bla;
// All done.
return exits.success(h);
}
};
I'm getting this error
error: A hook (`helpers`) failed to load!
error:
error: Attempted to `require('*-serv\api\helpers\testy.js')`, but an error occurred:
--
D:\*-serv\api\helpers\testy.js:28
fn: async function (inputs, exits) {
^^^^^^^^
SyntaxError: Unexpected token function.......
and if I remove the "async" and the "await" form the Controller, the ob object return null and I'm having this error
WARNING: A function that was initially called over 15 seconds
ago has still not actually been executed. Any chance the
source code is missing an "await"?
To assist you in hunting this down, here is a stack trace:
```
at Object.signup [as auth/signup] (D:\*-serv\api\controllers\AuthController.js:106:26)
The first guy from the comments is right.
After removing async from fn: async function (inputs, exists) {}; you need to setup sync: true which is false by default. It is described at helpers doc page at Synchronous helpers section.
So your code should look like this
module.exports = {
friendlyName: 'Testy',
description: 'Testy something.',
sync: true, // Here is essential part
inputs: {
bla: {
type: 'string'
}
},
exits: {
success: {
}
},
fn: function (inputs, exits) {
console.log({blabla:inputs.bla})
if(!inputs.bla) return exits.error(new Error('text not found'));
var h = "Hello "+ inputs.bla;
// All done.
return exits.success(h);
}
};
From the another side, you have a problem with async/await. The top most reason for this are
Not supported Node.js version - check that you current version support it
If you use sails-hook-babel or another Babel related solution, you may miss required plugin for async/await processing