问题
When running unit tests with Jest in react the window.crypto API is causing problems. I haven't found a way to incorporate crypto in Jest without installing other packages which is something I can't do. So without using another npm package is there a way to test functions that use: crypto.getRandomValues()
in them that doesn't crash Jest? Any links, advice, or tips are appreciated
回答1:
This should do it. Use the following code to set up the crypto
property globally. This will allow Jest to access window.crypto
and won't cause any issue.
const crypto = require('crypto');
Object.defineProperty(global.self, 'crypto', {
value: {
getRandomValues: arr => crypto.randomBytes(arr.length),
},
});
来源:https://stackoverflow.com/questions/52612122/how-to-use-jest-to-test-functions-using-crypto-or-window-mscrypto