sails helpers and machine spec - sails.js

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

Related

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

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: () => {}
})

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

Getting "Invalid exit definition" on Compilation of Sails Helper (Sails v1.0)

I'm getting the error
Invalid exit definition ("success"). Must be a dictionary-- i.e. plain JavaScript object like `{}`.
Invalid exit definition ("error"). Must be a dictionary-- i.e. plain JavaScript object like `{}`.
when doing sails lift. The error is on getRole.js
module.exports = {
friendlyName: 'Get Role',
description: '',
inputs: {
user_id: {
friendlyName: 'User Id',
description: 'The ID of the user to check role',
type: 'string',
required: true
}
},
exits: {
success: function (role){
return role;
},
error: function (message) {
return message;
}
},
fn: function (inputs, exits) {
User.findOne({ id: inputs.user_id } , function (err, user) {
if (err) return exits.err(err);
return exits.success(user.role);
});
}
};
This is a new error, and looking at my git, nothing has changed in my code since it successfully compiled. I understand the Sails version (v1.0) I'm using in beta, so I'm taking that into account.
Exits cannot be defined as functions. There is a special syntax (Machine Spec) to define exits. In your example this should work:
exits: {
error: {
description: 'Unexpected error occurred.',
},
success: {
description: 'Role was succesffuly fetched'
}
},
You can read more info about helper exits here: https://next.sailsjs.com/documentation/concepts/helpers
May changes occur on the last release 1.0.0-38. I've not checked underneath yet, but the way to execute helpers changed: on .exec() I get errors. Now, use .switch();

Unable to pass page objects to the spec file in protractor

We are new to Protractor and are going through the code to better understand its functionalists and in comparison with writing tests with selenium. As an exercise we have tried to automate the angularjs home page (http://www.angularjs.org) using page objects
Our TestSpec.js file is as follows
'use strict';
var DevelopPage = require('../test_11th/Develop_pom.js');
describe('angularjs homepage', function () {
var Devpage;
beforeEach(function () {
Devpage = new DevelopPage();
});
it('Develop page should be open', function () {
Devpage.click_develop().click();
//Devpage.Api_Reference();
//Devpage.func_link();
//Devpage.search('angular');
});
});
and the page object file Develop_pom.js is as follows
'use strict';
var DevelopPage = function () {
browser.get('http://www.angularjs.org');
};
DevelopPage.prototype = Object.create({}, {
click_develop: { function ()
{ browser.driver.findElement(By.linkText("Develop")).click(); }},
Api_Reference: { function ()
{ browser.driver.findElement(By.linkText("API Reference")).click(); }},
func_link: { function ()
{ browser.driver.findElement(By.linkText("function")).click(); }},
search: { : function (txt)
{ element(by.model('q')).click().sendKeys(txt); }}
});
while running it we are encountering the error
1) Exception loading: C:\Users\kirti.vm\AppData\Roaming\npm\node_modules\protractor\test_11th\AngularSpec.js Error
Message:
SyntaxError: Unexpected token (
Stacktrace:
SyntaxError: Unexpected token (
at require (module.js:380:17)
at Object. (C:\Users\kirti.vm\AppData\Roaming\npm\node_modules\protractor\test_11th\AngularSpec.js:4:21)
Finished in 0.012 seconds
1 test, 1 assertion, 1 failure
can you please let us know what and where we are going wrong. Can we not use page objects to implement our test and call those page objects in the spec script.
You need to export the page object at the end of the file:
module.exports = DevelopPage;
Take a look at the following example if you want to see a cleaner syntax:
https://github.com/angular/protractor/blob/master/website/test/e2e/api-page.js

Testing Angular $resource with external service

I'm trying to make some basic tests on REST requests I'm doing using Angular $resource.
The service code works just fine.
'use strict';
angular.module('lelylan.services', ['ngResource']).
factory('Device', ['Settings', '$resource', '$http', function(Settings, $resource, $http) {
var token = 'df39d56eaa83cf94ef546cebdfb31241327e62f8712ddc4fad0297e8de746f62';
$http.defaults.headers.common["Authorization"] = 'Bearer ' + token;
var resource = $resource(
'http://localhost:port/devices/:id',
{ port: ':3001', id: '#id' },
{ update: { method: 'PUT' } }
);
return resource;
}]);
I'm using the Device resource inside a directive and it works. The problems comes out
when I start making some tests on the services. Here is a sample test where I mock the
HTTP request using $httpBackend and I make a request to the mocked URL.
Unluckily it does not return anything, although the request is made. I'm sure about this
because if a request to another URL is made, the test suite automatically raises an error.
I've been spending lot of time, but no solutions. Here the test code.
'use strict';
var $httpBackend;
describe('Services', function() {
beforeEach(module('lelylan'));
beforeEach(inject(function($injector) {
var uri = 'http://localhost:3001/devices/50c61ff1d033a9b610000001';
var device = { name: 'Light', updated_at: '2012-12-20T18:40:19Z' };
$httpBackend = $injector.get('$httpBackend');
$httpBackend.whenGET(uri).respond(device)
}));
describe('Device#get', function() {
it('returns a JSON', inject(function(Device) {
device = Device.get({ id: '50c61ff1d033a9b610000001' });
expect(device.name).toEqual('Light');
}));
});
});
As the device is not loaded this is the error.
Expected undefined to equal 'Light'.
Error: Expected undefined to equal 'Light'.
I've tried also using the following solution, but it doesn't get into the function
to check the expectation.
it('returns a JSON', inject(function(Device) {
device = Device.get({ id: '50c61ff1d033a9b610000001' }, function() {
expect(device.name).toEqual('Light');
});
}));
Any suggestion or link to solve this problem is really appreciated.
Thanks a lot.
You were very close, the only thing missing was a call to the $httpBackend.flush();. The working test looks like follows:
it('returns a JSON', inject(function(Device) {
var device = Device.get({ id: '50c61ff1d033a9b610000001' });
$httpBackend.flush();
expect(device.name).toEqual('Light');
}));
and a live test in plunker: http://plnkr.co/edit/Pp0LbLHs0Qxlgqkl948l?p=preview
You might also want to check docs for the $httpBackend mock.
In later versions of angular, I'm using 1.2.0rc1 you also need to call this within a $apply or call $digest on a scope. The resource call isn't made unless you do something like this:
var o, back, scope;
beforeEach(inject(function( $httpBackend, TestAPI,$rootScope) {
o = TestAPI;
back = $httpBackend;
scope = $rootScope.$new();
}));
it('should call the test api service', function() {
back.whenGET('/api/test').respond({});
back.expectGET('/api/test');
scope.$apply( o.test());
back.flush();
});