Disable parse server logger during unit test of cloud code - unit-testing

all. I'm trying to implement an app that using parse server as backend.
And I'm trying to use mocha/chai to do the unit test for the cloud code function.
Like the code below.
const { expect } = require('chai');
const { server } = require('../index.js');
const Parse = require('parse/node');
let loggedUser;
let loggedUserSessionToken;
describe('SMS APIs', function() {
before('Initialize parse server.', function(done) {
Parse.initialize("appId");
Parse.serverURL = 'http://localhost:1337/parse';
done();
});
after('Close server', function(done) {
done();
server.close();
});
it('Pass', function(done) {
expect(1).to.equal(1);
done();
})
)};
After I run yarn mocha. The command line shows lots of log message. It is hard to read the mocha test result. like the picture below. Is there any method to turn off parse logger?
command line logger image

Take a look how the parse-server repo does it: helper.js
the key is to set 'silent: true' in the parse-server configuration.
I do this by using the wonderful config package, creating a test.js config that sets silent to true and then setting NODE_ENV=test when running my unit tests. Sounds like a lot to do, but this pattern is commonly reused for many things. Good luck!

Related

Do my tests need to be rewritten when mounting a setup() based Vue2.6 component with data param? Upgrading #vue/composition-api from 0.6.7 to 1.7.1

I'm having an exciting upgrade in a vue2 project using #vue/composition-api 0.6.7, trying to upgrade to 1.7.1.
Some tests are breaking and I'm noticing a pattern where the tests in question mount a component with the data parameter, as if they're reaching in and manipulating a ref
Example
// MyComponent.vue
<script>
export default defineComponent({
setup() {
const showModal = ref(false)
return {showModal}
}
})
</script>
Example test which was working before but now is broken.
it('should show the modal when the showModal ref is true', () => {
const wrapper = mount(MyComponent, {
data: {
showModal: true
}
});
expect(wrapper.find('#modal').exists()).toBe(true)
}
This makes sense to me that this broke in some ways because data is more of an options api thing and creating a ref is more of a composition-api thing-- probably more solidified as we went to 1.0 in the composition-api. That said, do you think that it should work?
When I rewrite the tests to NOT mount using the data prop and test it another way, the tests pass fine. I was expecting it to work as before and honestly not testing using the mount({data}), wrapper.setData(), or wrapper.vm seems like a better approach. I'm just looking for a confirmation or root cause why it worked before and not now.
Beyond this condensed code sample, I have tests using wrapper.setData({ serverResponse }) to simulate when a network call returns. This similarly breaks when I upgrade this composition-api package.

Use Cloud SDK in unit tests

I followed the guide here - https://sailsjs.com/documentation/concepts/testing
So my lifecycle.test.js looks like this:
var sails = require('sails');
// Before running any tests...
before(function(done) {
// Increase the Mocha timeout so that Sails has enough time to lift, even if you have a bunch of assets.
this.timeout(5000);
sails.lift({
// Your sails app's configuration files will be loaded automatically,
// but you can also specify any other special overrides here for testing purposes.
// For example, we might want to skip the Grunt hook,
// and disable all logs except errors and warnings:
hooks: { grunt: false },
log: { level: 'warn' },
}, function(err) {
if (err) { return done(err); }
// here you can load fixtures, etc.
// (for example, you might want to create some records in the database)
return done();
});
});
// After all tests have finished...
after(function(done) {
// here you can clear fixtures, etc.
// (e.g. you might want to destroy the records you created above)
sails.lower(done);
});
However in my test I am not able to use Cloud. I thought this was available to me because I saw in test suites here that they use Cloud - https://github.com/mikermcneil/ration/tree/master/test/suites
Do i have to modify my lifecycle.test.js to use Cloud?

Unit test a polymer web component that uses firebase

I have been trying to configure offline unit tests for polymer web components that use the latest release of Firebase distributed database. Some of my tests are passing, but others—that look nigh identical to passing ones—are not running properly.
I have set up a project on github that demonstrates my configuration, and I'll provide some more commentary below.
Sample:
https://github.com/doctor-g/wct-firebase-demo
In that project, there are two suites of tests that work fine. The simplest is offline-test, which doesn't use web components at all. It simply shows that it's possible to use the firebase database's offline mode to run some unit tests. The heart of this trick is the in the suiteSetup method shown below—a trick I picked up from nfarina's work on firebase-server.
suiteSetup(function() {
app = firebase.initializeApp({
apiKey: 'fake',
authDomain: 'fake',
databaseURL: 'https://fakeserver.firebaseio.com',
storageBucket: 'fake'
});
db = app.database();
db.goOffline();
});
All the tests in offline-test pass.
The next suite is wct-firebase-demo-app_test.html, which test the eponymous web component. This suite contains a series of unit tests that are set up like offline-test and that pass. Following the idea of dependency injection, the wct-firebase-demo-app component has a database attribute into which is passed the firebase database reference, and this is used to make all the firebase calls. Here's an example from the suite:
test('offline set string from web component attribute', function(done) {
element.database = db;
element.database.ref('foo').set('bar');
element.database.ref('foo').once('value', function(snapshot) {
assert.equal(snapshot.val(), 'bar');
done();
});
});
I have some very simple methods in the component as well, in my attempt to triangulate toward the broken pieces I'll talk about in a moment. Suffice it to say that this test passes:
test('offline push string from web component function', function(done) {
element.database = db;
let resultRef = element.pushIt('foo', 'bar');
element.database.ref('foo').once('value', function(snapshot) {
assert.equal(snapshot.val()[resultRef.key], 'bar');
done();
});
});
and is backed by this implementation in wct-firebase-demo-app:
pushIt: function(at, value) {
return this.database.ref(at).push(value);
},
Once again, these all pass. Now we get to the real quandary. There's a suite of tests for another element, x-element, which has a method pushData:
pushData: function(at, data) {
this.database.ref(at).push(data);
}
The test for this method is the only test in its suite:
test('pushData has an effect', function(done) {
element.database = db;
element.pushData('foo', 'xyz');
db.ref('foo').once('value', function(snapshot) {
expect(snapshot.val()).not.to.be.empty;
done();
});
});
This test does not pass. While this test is running, the console comes up with an error message:
Your API key is invalid, please check you have copied it correctly.
By setting some breakpoints and walking through the execution, it seems to me that this error comes up after the call to once but before the callback is triggered. Note, again, this doesn't happen with the same test structure described above that's in wct-firebase-demo-app.
That's where I'm stuck. Why do offline-test and wct-firebase-demo-app_test suites work fine, but I get this API key error in x-element_test? The only other clue I have is that if I copy in a valid API key into my initializeApp configuration, then I get a test timeout instead.
UPDATE:
Here is a (patched-together) image of my console log when running the tests.:
To illustrate the issue brought up by tony19 below, here's the console log with just pushData has an effect in x-element_test commented out:
The offline-test results are apparently false positives. If you check the Chrome console, offline-test actually throws the same error:
The error doesn't affect the test results most likely because the API key validation occurs asynchronously after the test has already completed. If you could somehow hook into that validation, you'd be able to to catch the error in your tests.
Commenting out all tests except for offline firebase is ok shows the error still occurring, which points to suiteSetup(). Narrowing the problem down further by commenting 2 of the 3 function calls in the setup, we'll see the error is caused by the call to firebase.initializeApp() (and not necessarily related to once() as you had suspected).
One workaround to consider is wrapping the Firebase library in a class/interface, and mocking that for unit tests.

Karma + Jasmine reporting 0 tests run when there are tests

I'm trying to run some Jasmine tests in Karma but the tests are failing because it's saying that it ran 0 of 0 tests. Can someone tell me what I'm doing wrong?
The async request mock fires and hits the callback. Even when I go to the debugger, it says 2 tests completed in the debugger, but failing in the console. What gives?
describe('User Info Tests:', function () {
describe('Fetch User Info:', function () {
it("User Name should match", function(done) {
// mock async request
getUserProfile(1, 2, function (userProfile) {
var match = userProfile.displayName === 'Unit Test User';
expect(match).toBeTruthy();
done();
}, function (msg) {
done();
throw msg;
}); 
});
});
});
See the screenshot below of the debug console of the tests running. You will see the tests ran with a status of SUCCESS.
So the problem was I wasn't including the karam-requirejs plugin in the karam.conf.js file. Apparently it doesn't want you to include your own copy of require.js in the files collection. Once I added that plugin in, everything just worked.
frameworks: ['jasmine-jquery', 'jasmine', 'requirejs'],
plugins: [
'karma-phantomjs-launcher',
'karma-chrome-launcher',
'karma-jasmine-jquery',
'karma-jasmine',
'karma-requirejs'
],
Make sure the karma-requirejs plugin is actually installed through npm and in your package.json as well!

load json file for jasmine test with angular.js

I have mock data in an external json file that I want to have available for Jasmine unit tests in Angular.js. Unfortunately I am not approved to run node.js in my dev environment, so the usual karma examples don't apply to me.
I have tried:
beforeEach(inject(function ($injector, $http) {
console.log('this gets called');
$http.get('/mockData/surveySetup.json').success(function (data) {
console.log('this never gets called');
}).error(function () {
console.log('this never gets called');
});
}));
The console.log outside of the $http.get gets called, but the ones inside $http.get never fire, and I don't see a call to the json file in chrome's network tab.
What can I do to load this file to use in my tests? At the end of the day I just need to have access to the data in the .json file so I can refer to it in my unit tests.
Thanks in advance.
I found that I needed to convert my .json file to an Angular service (actually an Angular constant worked for my purposes). Then my external file was easy to grab in my tests, like so:
var setupData = $injector.get('SetupData');
$httpBackend.whenGET('/surveySetup').respond(setupData);
$httpBackend.flush();
Not sure what exactly are going to achieve but usually you can configure this by using $httpBackend which can be configured to mock the actual requests from any of your code (you may also need to setup with your URL syntax in this case but anyway this the common case for the unit tests. In this case you don't need to read the JSON file you can just provide the JS object inside of the $httpBackend configuration for that URL and when this URL is to be invoked $httpBackend will return the specified object. Look at: $httpBackend