My bootstrap.test.js file is as follows.
var Sails = require('sails');
before(function (done) {
process.env.NODE_ENV = 'test';
process.env.PORT = 9999;
Sails.lift({
models: {
connection: 'localDiskDb',
migrate: 'drop'
}
}, function (err, server) {
sails = server;
if (err) return done(err);
sails.log.info('***** Starting tests... *****');
console.log('\n');
done(null, sails);
});
});
after(function (done) {
sails.lower(done);
});
A very simple modal test is available at tests/integration/controllers/AuthController.spec.js as follows.
var assert = require('assert');
describe('PackagesModel', function() {
describe('Sample Test1', function() {
it('Sample test', function (done) {
assert.equal(-1, [1,2,3].indexOf(4));
done();
});
});
});
I try to run the mocha tests as follows.
node ./node_modules/mocha/bin/mocha tests/bootstrap.test.js tests/integration/**/*.spec.js
This results in the following error.
1) "before all" hook
0 passing (1s)
1 failing
1) "before all" hook:
Uncaught TypeError: policy.bind is not a function
at Object.policyHookDef.normalizePolicy (node_modules/sails/lib/hooks/policies/index.js:206:38)
at normalize_each_policy (node_modules/sails/lib/hooks/policies/index.js:192:34)
at arrayMap (node_modules/#sailshq/lodash/lib/index.js:1556:25)
at Function.map (node_modules/#sailshq/lodash/lib/index.js:6886:14)
at Object.policyHookDef.normalizePolicy (node_modules/sails/lib/hooks/policies/index.js:191:13)
at node_modules/sails/lib/hooks/policies/index.js:172:59
at node_modules/#sailshq/lodash/lib/index.js:3228:15
at baseForOwn (node_modules/#sailshq/lodash/lib/index.js:2199:14)
at node_modules/#sailshq/lodash/lib/index.js:3198:18
at Function.<anonymous> (node_modules/#sailshq/lodash/lib/index.js:3501:13)
at node_modules/sails/lib/hooks/policies/index.js:167:11
at node_modules/#sailshq/lodash/lib/index.js:3228:15
at baseForOwn (node_modules/#sailshq/lodash/lib/index.js:2199:14)
at node_modules/#sailshq/lodash/lib/index.js:3198:18
at Function.<anonymous> (node_modules/#sailshq/lodash/lib/index.js:3501:13)
at Hook.policyHookDef.buildPolicyMap (node_modules/sails/lib/hooks/policies/index.js:150:9)
at Hook.wrapper [as buildPolicyMap] (node_modules/#sailshq/lodash/lib/index.js:3250:19)
at Hook.policyHookDef.bindPolicies (node_modules/sails/lib/hooks/policies/index.js:67:27)
at Sails.wrapper (node_modules/#sailshq/lodash/lib/index.js:3250:19)
at Sails.emitter.emit (node_modules/sails/lib/app/private/after.js:50:11)
at Router.flush (node_modules/sails/lib/router/index.js:360:9)
at Router.wrapper [as flush] (node_modules/#sailshq/lodash/lib/index.js:3250:19)
at Router.load (node_modules/sails/lib/router/index.js:136:8)
at Array.wrapper (node_modules/#sailshq/lodash/lib/index.js:3250:19)
at listener (node_modules/sails/node_modules/async/lib/async.js:600:42)
at node_modules/sails/node_modules/async/lib/async.js:542:17
at _arrayEach (node_modules/sails/node_modules/async/lib/async.js:85:13)
at Immediate.taskComplete (node_modules/sails/node_modules/async/lib/async.js:541:13)
Any ideas on what might lead to this?
For anyone who might come across the same error in the future, the reason for the error was the usage of sails-must middleware that I was using. In my policies.js file I had rules like the following.
MyController: {
createStatement : ['isAuthenticated',must().have(runner).priviledge],
getStatement :['isAuthenticated',must().have(driver).priviledge.or.have(clerk).priviledge]
},
When the above lines were removed, tests ran. I know that this is not a complete answer with the cause of the error. But should be useful to someone else who comes across the same problem.
I switched to the approach mentioned in this SO thread to make my ACL logic.
Hope this helps!
Related
I have the following code:
export function backofficeAuthenticate(username, password) {
cy.session(['Login'], () => {
cy.request({
log: false,
method: 'POST',
url: getBackUrl('/login.htm'),
qs: {
redir: getBackUrl('/back'),
},
followRedirect: false,
body: {
'Login_login-email': username,
'Login_login-password': password,
'action[Login_login:login]': 'login',
},
});
});}
And I am calling a function to login like that:
export function loginWithAdmin() {
backofficeAuthenticate(Cypress.env('WEB_LOGIN_USERNAME'), Cypress.env('WEB_LOGIN_PASSWORD'));
}
My code in the test is:
import { loginWithAdmin, httpAuthentication } from '../../cypress/support/bestreviews.js';
describe('Dashboard types quick smoke', () => {
const endpoints = [
'/dashboard',
'/dashboard/articles',
'/dashboard/archive',
'/dashboard/syndicated',
'/dashboard/tribunearticles',
'/dashboard/giftguides',
'/dashboard/blogposts',
];
endpoints.forEach((endpoint) => {
it(endpoint, () => {
cy.visitBackOffice(endpoint);
httpAuthentication();
loginWithAdmin();
cy.checkErrorFree();
cy.get('.dashboard-entries').should('exist');
cy.get('[data-content="topic-info"]').should('exist');
});
});
});
After I execute the code, I always got an error:
(uncaught exception) TypeError: Cannot read properties of null
(reading 'style') TypeError The following error originated from your
application code, not from Cypress.
Cannot read properties of null (reading 'style')
When Cypress detects uncaught errors originating from your application
it will automatically fail the current test.
This behavior is configurable, and you can choose to turn this off by
listening to the uncaught:exception event.Learn more
Does anyone know what I am missing? I think the problem is with cypress session, but not sure how to proceed...
To make sure that cypress catches exceptions generated from your application you can add this in cypress/support/e2e.js
Cypress.on('uncaught:exception', (err, runnable) => {
// returning false here prevents Cypress from
// failing the test
return false
})
Note: One thing to note is that if you add this, cypress will not catch exceptions generated from your application, which is not a good practice, because you want your tests to catch exceptions.
If a mocha test looks like this
describe("create a user") {
before("login to system") {}
it("execute assertion") {}
after("delete the user") {}
}
If either before or it block failed, does the after block still execute or no?
Yes, when test fails it will run after hook.
This code:
before("login to system", () => {
console.log("BEFORE")
throw new Error('error');
})
it('testing...', (done) => {
console.log("IT")
done();
});
after("delete the user", () => {
console.log("AFTER")
})
Output this:
BEFORE
1) "before all" hook: login to system for "testing..."
AFTER
0 passing (14ms)
1 failing
1) States Get
"before all" hook: login to system for "testing...":
Error: error
at Context.<anonymous> (test\index.js:22:11)
at processImmediate (node:internal/timers:463:21)
Also you can check this github discussion: #1612 where here says:
Please see the example below, showing that after is correctly invoked after the beforeEach failure
The code
// example.js
before(function() {
console.log('before');
});
after(function() {
console.log('after');
});
describe('suite', function() {
beforeEach(function() {
throw new Error('In beforeEach');
});
afterEach(function() {
console.log('afterEach');
});
it('test', function() {
// example
});
});
And the output.
// Test run
$ mocha example.js
before
․afterEach
after
0 passing (7ms)
1 failing
1) suite "before each" hook:
Error: In beforeEach
at Context.<anonymous> (/Users/dstjules/git/mocha/example.js:11:11)
at callFn (/usr/local/lib/node_modules/mocha/lib/runnable.js:251:21)
at Hook.Runnable.run (/usr/local/lib/node_modules/mocha/lib/runnable.js:244:7)
at next (/usr/local/lib/node_modules/mocha/lib/runner.js:259:10)
at Immediate._onImmediate (/usr/local/lib/node_modules/mocha/lib/runner.js:276:5)
at processImmediate [as _immediateCallback] (timers.js:358:17)
Sentry by defaults has integration for console.log to make it part of breadcrumbs:
Link: Import name: Sentry.Integrations.Console
How can we make it to work for bunyan logger as well, like:
const koa = require('koa');
const app = new koa();
const bunyan = require('bunyan');
const log = bunyan.createLogger({
name: 'app',
..... other settings go here ....
});
const Sentry = require('#sentry/node');
Sentry.init({
dsn: MY_DSN_HERE,
integrations: integrations => {
// should anything be handled here & how?
return [...integrations];
},
release: 'xxxx-xx-xx'
});
app.on('error', (err) => {
Sentry.captureException(err);
});
// I am trying all to be part of sentry breadcrumbs
// but only console.log('foo'); is working
console.log('foo');
log.info('bar');
log.warn('baz');
log.debug('any');
log.error('many');
throw new Error('help!');
P.S. I have already tried bunyan-sentry-stream but no success with #sentry/node, it just pushes entries instead of treating them as breadcrumbs.
Bunyan supports custom streams, and those streams are just function calls. See https://github.com/trentm/node-bunyan#streams
Below is an example custom stream that simply writes to the console. It would be straight forward to use this example to instead write to the Sentry module, likely calling Sentry.addBreadcrumb({}) or similar function.
Please note though that the variable record in my example below is a JSON string, so you would likely want to parse it to get the log level, message, and other data out of it for submission to Sentry.
{
level: 'debug',
stream:
(function () {
return {
write: function(record) {
console.log('Hello: ' + record);
}
}
})()
}
I am trying to write a unit test for my store in react application.
Unit test looks like:
import FRIENDS from '../../constants/friends';
import FriendsStore from '../friends_store';
jest.dontMock('../../constants/friends');
jest.dontMock('../friends_store');
describe('FriendsStore', () => {
let AppDispatcher;
let callback;
let addFriends = {
actionType: FRIENDS.ADD_FRIENDS,
name: 'Many'
};
let removeFriend = {
actionType: FRIENDS.REMOVE_FRIENDS,
id: '3'
};
beforeEach(function () {
AppDispatcher = require('../../dispatcher/app_dispatcher');
callback = AppDispatcher.register.mock.calls[0][0];
});
it('Should initialize with no friends items', function () {
var all = FriendsStore.getAll();
expect(all).toEqual([]);
});
});
And when I executed with jest statement, I've got the error message:
Using Jest CLI v0.4.0
FAIL scripts/stores/__tests__/friends_store-test.js (0.811s)
● FriendsStore › it Should initialize with no friends items
- TypeError: Cannot read property 'calls' of undefined
at Spec.<anonymous> (/Volumes/Developer/reactjs/app5/scripts/stores/__tests__/friends_store-test.js:33:41)
at jasmine.Block.execute (/Volumes/Developer/reactjs/app5/node_modules/jest-cli/vendor/jasmine/jasmine-1.3.0.js:1065:17)
at jasmine.Queue.next_ (/Volumes/Developer/reactjs/app5/node_modules/jest-cli/vendor/jasmine/jasmine-1.3.0.js:2098:31)
at null._onTimeout (/Volumes/Developer/reactjs/app5/node_modules/jest-cli/vendor/jasmine/jasmine-1.3.0.js:2088:18)
at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)
1 test failed, 0 tests passed (1 total)
Run time: 1.028s
It seems to be, that jest can not find the calls property. What am I doing wrong?
I had a similar issue.
Making the following change should resolve the issue:
beforeEach(function () {
AppDispatcher = require('../../dispatcher/app_dispatcher');
FriendsStore = require('/path/to/store'); //**load in store**
callback = AppDispatcher.register.mock.calls[0][0];
});
Working with ReactJS v15.2.1 & Jest v14.0.0
This also worked on ReactJS v14 too.
I'm unit testing a controller's method. My app fires off a few GET requests on app start, and I'm getting unexpected request errors when I run my tests.
Here is the login method of my controller. Note: I'm using angular classy (thus the nonstandard syntax):
login: function() {
var self = this,
params,
loginSuccess,
user;
if (self.$.user.email === '' || self.$.user.password === '') {
self.$notification.alert({
title: "Error",
message: "Email and password can't be blank!"
});
} else {
params = {
user: self.$.user,
position: self.Geolocation.currentPosition
};
self.$session.login(params).then(loginSuccess);
}
};
Here is the test:
describe("LoginController", function() {
var scope, $rootScope, createController, $controller,
$httpBackend, $session, session, $notification;
var emptyCredentials = {
email: "bleh",
password: ""
};
beforeEach(angular.mock.module('myapp'));
beforeEach(inject(function($injector){
jasmine.getJSONFixtures().fixturesPath='base/unit/fixtures';
$httpBackend = $injector.get("$httpBackend");
$httpBackend
.when('GET', 'http://myapp.com:3000/api/v2/apps/3?app_id=3')
.respond(200, getJSONFixture('apps.json'));
$httpBackend
.when('GET', 'http://myapp.com:3000/api/v2.2/locations?app_id=3')
.respond(200, getJSONFixture('locations.json'));
$httpBackend
.when('GET', 'http://myapp.com:3000/api/v2/users/me?app_id=3')
.respond(200, getJSONFixture('me.json'));
$session = $injector.get("$session");
// mock session so that session.loggedIn doesn't return true
// on subsequent tests
session = {
setUser: function() {
},
loggedIn: function() {
return false;
},
authPath: function() {
return false;
},
login: $session.login
};
$rootScope = $injector.get("$rootScope");
$controller = $injector.get("$controller");
$notification = $injector.get("$notification");
scope = $rootScope.$new();
createController = function () {
return $controller('LoginController', {
$scope: scope,
$session: session,
$notification: $notification
});
};
// spies on $notification.alerts
spyOn($notification, 'alert');
}));
afterEach (function () {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
$httpBackend.resetExpectations();
});
it('should show alert on empty login credentials', function() {
$httpBackend.expectGET('http://myapp.com:3000/api/v2/apps/3?app_id=3');
$httpBackend.expectGET('http://myapp.com:3000/api/v2.2/locations?app_id=3');
$httpBackend.expectGET('http://myapp.com:3000/api/v2/users/me?app_id=3');
var controller = createController();
scope.user = emptyCredentials;
scope.login();
$httpBackend.flush();
expect($notification.alert).toHaveBeenCalledWith({
title: "Error",
message: "Email and password can't be blank!"
});
});
When I run karma, I get these errors:
Error: Unexpected request: GET http://myapp.com:3000/api/v2/apps/3?app_id=3
Expected GET http://myapp.com:3000/api/v2/apps/3?app_id=3
at $httpBackend (/Users/myapp/vendor/angular-mocks/angular-mocks.js:1178:9)
at sendReq (/Users/myapp/vendor/angular/angular.js:8315:9)
at serverRequest (/Users/myapp/vendor/angular/angular.js:8049:16)
at wrappedCallback (/Users/myapp/vendor/angular/angular.js:11520:81)
at wrappedCallback (/Users/myapp/vendor/angular/angular.js:11520:81)
at /Users/myapp/vendor/angular/angular.js:11606:26
at Scope.$eval (/Users/myapp/vendor/angular/angular.js:12632:28)
at Scope.$digest (/Users/myapp/vendor/angular/angular.js:12444:31)
at Function.$httpBackend.flush (/Users/myapp/vendor/angular-mocks/angular-mocks.js:1438:16)
at null.<anonymous> (/Users/myapp/test/unit/controllers/login_controller.test.js:104:18)
Error: Unexpected request: GET http://myapp.com:3000/api/v2.2/locations?app_id=3
Expected GET http://myapp.com:3000/api/v2/apps/3?app_id=3
at $httpBackend (/Users/myapp/vendor/angular-mocks/angular-mocks.js:1178:9)
at sendReq (/Users/myapp/vendor/angular/angular.js:8315:9)
at serverRequest (/Users/myapp/vendor/angular/angular.js:8049:16)
at wrappedCallback (/Users/myapp/vendor/angular/angular.js:11520:81)
at wrappedCallback (/Users/myapp/vendor/angular/angular.js:11520:81)
at /Users/myapp/vendor/angular/angular.js:11606:26
at Scope.$eval (/Users/myapp/vendor/angular/angular.js:12632:28)
at Scope.$digest (/Users/myapp/vendor/angular/angular.js:12444:31)
at Function.$httpBackend.verifyNoOutstandingExpectation (/Users/myapp/vendor/angular-mocks/angular-mocks.js:1470:16)
at null.<anonymous> (/Users/myapp/test/unit/controllers/login_controller.test.js:75:18)
FYI Line 104 of login_controller.test.js is $httpBackend.flush(). Line 75 of login_controller.test.js is $httpBackend.verifyNoOutstandingExpectation().
I believe the $httpBackend.when() are called before the app is started (and thus before app start's requests are fired), but maybe that's not true. Curiously enough, the error reports that it found an unexpected request of XXX, and the very next line says it expected a request of the same path! So not sure why that's happening.
Running Angular 1.2.21, Angular Mocks 1.2.21
Can anyone explain to me why I'm seeing this error, and what I can do to properly flush and handle those requests?
Thanks.
I figured out what was going on:
It turns out a vendor plugin was extending the native String object, redefining a match() method. This was conflicting with how angular-mocks was comparing the expectation to the request, and thus threw the error falsely.
If you happen to experience this issue (where expected request and the observed request are identical), look for plugins or libraries that extend the native String object.
Mootools, for example, does this and would cause this issue.
The problem is that now $http uses promises even for request interceptors and so the verification is happening before $httpBackend gets the request. Try adding $rootScope.$digest(); and you will get "No more request expected".
Refer: https://github.com/angular/angular.js/issues/5453