Mock secure origin for auth0-spa-js in Jest tests - javascript

Trying to setup jest tests around auth0-spa-js but getting error 'auth0-spa-js must run on a secure origin' when attempting to await createAuth0Client(config). Whats the best way to mock secure origin in jest tests?

After digging into auth0 code to see what it wants, i gave it global.crypto.subtle = {} and it seems to have satisfied it, the error has gone, the tests pass:
const JSDOM = require('jsdom').JSDOM
Object.defineProperty(global.self, 'crypto', {
value: {
getRandomValues: arr => crypto.randomBytes(arr.length)
}
})
global.crypto.subtle = {} // this gets around the 'auth0-spa-js must run on a secure origin' error

Related

Simple Web Worker not working in SvelteKit on Firefox 106.0.5

Inside my main file, I have
const loadWorker = async () => {
const SyncWorker = await import("$lib/canvas.worker?worker");
syncWorker = new SyncWorker.default();
syncWorker?.postMessage({});
};
Then in my unmount I have
onMount(() => {
console.log("Canvas: mounted");
loadWorker();
});
Then in my canvas.worker.ts file, I have a simple
onmessage = () => {
console.log("Hello from the worker!");
};
export {};
This message prints successfully in Chrome, but in firefox all I get is
SyntaxError: import declarations may only appear at top level of a module
Is this because the worker is stored on my local system, and maybe there's a special flag to allow loading of system files as workers (as that seems it may be a security concern)? Firefox docs say that my browser should support workers.
Well, I should've read the documentation better.
service workers only work in the production build, not in development.
To test it locally, use vite preview
https://kit.svelte.dev/docs/service-workers
Or in my case, "npm run build && npm run preview" worked.

How to use Mocha to test on client-side WebSocket? Receiving a ReferenceError: WebSocket is not defined

I am writing a wrapper around the HTML5 WebSocket object, and I am testing the entire project (the node server side and the client side) with mocha.
When I run my tests against my wrapper, I get a ReferenceError: WebSocket is not defined from mocha. I think that is something related to the fact that mocha is used to test node stuff, but I can't find something that confirm my hipothesis and show me how to properly setup my test environment.
Right now everything is very simple, my test script is just:
"test": "mocha --recursive 'src/**/__tests__/*.js'"
My wrapper is:
function Signal() {
this.socket = null
}
Signal.prototype.connect = function connect(url) {
this.socket = new WebSocket(url)
}
My tests are just checking if calling the connect method with a non-responding server blows:
// I use chai as assertion library
describe('connect', () => {
it('blows if the server doesn\'t exist or respond', () => {
const signal = new Signal()
const connect = () => signal.connect('wss://fakeurl:12345')
expect(connect).to.throw()
})
})
I also tried with jest. It doesn't throw the ReferenceError but always tells me that the test is passing... even if I manually throw an error in the connect method.
What am I missing? Any idea?

Tests fail when I save (using `--watch` in test script config) but if I re-run manually they pass?

Not a big problem per se but I'm curious as to what's causing this behavior. I'm writing some very basic code to learn how to do some testing. I'm using jestjs for testing a node/express application, and am presently testing the development version of my project locally. All versions are up to date (most current available).
In the configuration for jest I have the following setup:
...
"test": "./node_modules/.bin/env-cmd -f ./config/test.env jest --watch"
},
"jest": {
"testEnvironment": "node",
"verbose": true
}
And my environment configuration (as referenced above by the env-cmd:
PORT=3000
SENDGRID_API_KEY=<API KEY>
JWT_SECRET=<JWT SECRET>
MONGODB_URL=mongodb://127.0.0.1:27017/task-manager-api-test
The --watch flag is supposed to work sort of like nodemon - whenever I save my test file it re-runs the tests. The problem seems to be that whenever I save the file some of the tests fail (it's fairly inconsistent as to which tests fail) - but if I manually re-run the tests (--watch gives me a CLI that allows me to re-run tests with a keypress) the tests pass.
I'm using the following in my test file to make sure that the DB instance has no data in it before running the tests:
// User to seed DB
const testUserUID = new mongoose.Types.ObjectId()
const testUser = {
_id: testUserUID,
name: 'firstName lastName',
email: 'automatedTest#test.com',
password: 'test1234',
tokens: [{
token: jwt.sign({ _id: testUserUID }, process.env.JWT_SECRET)
}]
}
// Setup
beforeEach(async () => {
await User.deleteMany()
await new User(testUser).save()
})
An Example of one of my tests:
test('Should signup a user', async () => {
await request(app)
.post('/users')
.send({
name: 'hardcodeFirst hardcodeLast',
email: 'hardcodeTest#test.com',
password: 'test1234'
})
.expect(201)
})
One of the more common errors I am getting is a MongoError:
MongoError: E11000 duplicate key error collection: task-manager-api-test.users index: email_1 dup key: { : "automatedtest#test.com" }
The other errors that are being thrown are related to the tests failing - so I'm getting values that the test does not expect.
I've tried googling some stuff related to testing async with jest but I haven't found anything that isn't shown in the documentation about how to use promises or async/await with jest. I've verified that my environment variables aren't pointing at my remote DB instance. I've run the tests in my normal (non-vscode) terminal. I've also verified that the tests always pass when using the --watch CLI (pressing Enter or a repeatedly) - the tests are only failing when I save the test file and it automatically re-runs due to the --watch flag.
Talking to one of my developer buddies it was suggested that I've possibly somehow created some sort of race condition. That would be a new situation for me if that's the case!
Thanks in advance for taking a look/any help offered!
EDIT: Included .env for my test environment
--watch flag works only for github repos. u should add watchAll
"test": "env-cmd -f ./config/test.env jest --watch"
rest of your code looks fine.

Testing internal functions in Mocha ESlint error

I'm currently developing an Nodejs application and carrying out some unit tests (I'm using Mocha, Chai and Sinon).
I ran into a little ESlint error when I exported and tested an internal function.
function _buildPayload(){
//....
}
module.exports = { _buildPayload };
Then in my test script
const {_buildPayload} = requires('./someModule')
describe('Test',function(){
it('Should work',function(){
let expected = _buildPayload();
})
})
When I write the let expected = _buildPayload(); ESlint returns the following error:
error Shouldn't be accessing private attribute '_buildPayLoad'
My question is should I change the name of my function to not represent and internal even though it is?
#philipisapain makes a good point that testing internal methods may not be necessary. If you do need to do it, you have a couple options:
Disable the rule by placing /* eslint-disable rule-name */ at the top of any test scripts that call private methods.
Disable the rule in all test scripts using a glob config in your .eslintrc, provided you're using at least ESLint v4.1.0:
"overrides": [{
"files": ["*.test.js"],
"rules": [{
"rule-name": "off"
}]
}]

Integrating Jest and Rewire

Working on getting a project transitioned over from Mocha to Jest to take advantage of the speed in running tests as well as the Jest framework itself and running into an issue. Rewire is used pretty extensively in the codebase and I'm having an issue when running the gulp-jest task and only for those files that use rewire. I assume it has something to do with modules loading or not loading, but I'm stumped. Here's the really bare-bones gulp task, doesn't have much to it. I've already run through an extensive codemod on the codebase and many tests pass, just not those that use rewire.
gulp.task('jest', function() {
process.env.NODE_ENV = 'test';
return gulp.src('name/path').pipe(
jest({
preprocessorIgnorePatterns: ['<rootDir>/node_modules/'],
automock: false,
resetModules: true,
setupFiles: ['./jestsetup.js']
})
);
});
gulp.task('newtest', function(callback) {
runSequence('env', 'jest', callback);
});
Any time the rewire-related files are run, they complain about the file not being found. Am I missing anything here? I'm certain the modules themselves have the correct path set for the require.
Here's the actual error from jest/rewire:
FAIL path/to/folder/file/app.test.js
● Test suite failed to run
Cannot find module '../../../../path/to/folder/file/app'
at Function.Module._resolveFilename (module.js:469:15)
at internalRewire (node_modules/rewire/lib/rewire.js:23:25)
at rewire (node_modules/rewire/lib/index.js:11:12)
at Object.<anonymous (path/to/folder/file/app.test.js:10:14)
at process._tickCallback (internal/process/next_tick.js:109:7)
Using node 6.X, jest 20.x
Thanks in advance!
Jest has its own mechanism of mocking import, it's called jest.mock.
You will need to switch to using that instead of rewire.
Example
// banana.js
module.exports = () => 'banana';
// __tests__/test.js
jest.mock('../banana');
const banana = require('../banana'); // banana will be explicitly mocked.
banana(); // will return 'undefined' because the function is auto-mocked.
example was taken from here
To my surpise, Proxyquire was not compatible with jest. To mock a dependency you would need to utilize a mocking library, like rewiremock.
Please have a look at this answer and this REPL example on how to successfully mock dependent packages.

Categories

Resources