Ember.JS concurrency task, perform() is not a function - javascript

I was trying to convert a function over to a task. Here is the original code:
Call:
this.socketConnect(endpoint, token);
Function:
socketConnect = async (token, endpoint) => {
this.socket = new WebSocket(endpoint + '?auth=' + token);
this.socket.addEventListener('open', () => {
this.socket.addEventListener('message', event => this.handleMessage(event));
this.socket.addEventListener('close', event => this.retryConnection(event, endpoint));
});
}
I've been following structure on implementing Ember tasks. It all compiles with no issue, however when it gets called, it outputs that this.socketConnect(...) is not a function. Before hand I didn't have the return below and it output that this.socketConnect wasn't a function. Here is my current code for a task.
Import:
import { task } from 'ember-concurrency';
Call:
this.socketConnect(endpoint, authToken).perform();
Function:
#task *socketConnect(endpoint, token) {
yield async () => {
this.socket = new WebSocket(endpoint + '?auth=' + token);
this.socket.addEventListener('open', () => {
this.socket.addEventListener('message', event => this.handleMessage(event));
this.socket.addEventListener('close', event => this.retryConnection(event, endpoint));
});
return;
};
}
New to this, so I'm guessing there's something small I'm missing. It matches other uses. Also if anyone could help on the benefits of switching a websocket generation function to a task? Any help would be appreciated, thank you.

The #task decorator isn't part of the official ember-concurency package yet. The official version lives in ember-concurrency-decorators for now. You'll need to
ember install ember-concurrency-decorators
and then you can do
import { task } from 'ember-concurrency-decorators';
To use it.
Alternatively you can use a different syntax if you don't want another dependency.
import { task } from 'ember-concurrency';
class Foo {
#(task(function*() {
// ...
}).restartable())
doStuff;
executeTheTask() {
this.doStuff.perform();
}
}
To call the task the syntax is:
this.socketConnect.perform(endpoint, authToken);
As you're not calling socketConnect directly, you want to call the method that ember concurrency generates for you.

Related

Export reusable Javascript function in Cypress test spec file

I am trying to have a reusable component in my Cypress spec file, which is organized by our system 'services'. There are code pieces that I would like to make available as component for other JS files.
However, I found the 'import' statement results in running of B.js's test cases, and I cannot find a way to avoid 'Testcase B' from running.
I know there is custom commands in Cypress, but in my case, I would like to use pure JS to organize my component. Thank you.
A.js
import {functionInB as helloB } from "./B"
describe(`A`, () => {
it(`01 Testcase A`, () => {
let result = helloB()
console.log(result)
})
});
B.js
describe(`B`, () => {
it(`01 Testcase B`, () => {
//let result = Hello2()
console.log("inside hello B")
})
});
export function functionInB(){
return "Do something in functionInB"
}
There doesn't seem to be a way to stop a script running on import (or require() or dynamic import()).
In Python __main__ (docs) is used to determine if a module is called at the "top level".
if __name__ == "__main__":
# execute only if run as a script
main()
It's a bit hacky, but you can use Cypress.spec.name to do the same thing and only run B's code when it is the current spec.
if (Cypress.spec.name === 'B.js') {
describe(`B`, () => {
it(`01 Testcase B`, () => {
//let result = Hello2()
console.log("inside hello B")
})
});
}
export function functionInB(){
return "Do something in functionInB"
}
The "javascript way" would be to move functionInB() to a utility file and import in it both tests, but I guess you already know that.

Handing C# .NET events with edge.js in Node.js for electron

I need to do some calls from my js to my C# DLL in my Electron project and it works fine in this way:
c#
namespace Electron.Wrapper
{
public class QueryWrapper
{
public async Task<object> OnQuery(dynamic request)
{
...
return ..;
}
}
}
js
let edge = require('electron-edge-js');
let queryWrapperQuery = edge.func({
assemblyFile: '..dllUrl..',
typeName: 'Electron.Wrapper.QueryWrapper',
methodName: 'OnQuery'
});
window.query = function (options) {
queryWrapperQuery(JSON.stringify(options), function (error, result) {
...
});
}
The problem is that I use an external DLL that triggers async events sometimes, so I need find a way for listening the .NET events from js.
I found this way for resolve my problem but I think isn't the right way because I need a class library for Electron and I don't know how use it with also the previous way and probabily I don't need a WebSocketServer.
A .Net and js sample will be valued.
Thanks,
Andrea
Update 1
I found this way, cold be the right one? I'm trying to implement .net, any suggestions?
I found a good way:
C#:
public Task<object> WithCallback(IDictionary<string, object> payload)
{
Func<object, Task<object>> changed = (Func<object, Task<object>>)payload["changed"];
return Task.Run(async () => await OnQuery(payload["request"], changed));
}
js:
var withCallback = edge.func({
assemblyFile: '..dllUrl..',
typeName: 'Electron.Wrapper.QueryWrapper',
methodName: 'WithCallback'
});
window.query = function (options) {
function triggerResponse(error, result) {
...
}
withCallback({
changed: (result) => triggerResponse(null, result),
request: JSON.stringify(options)
}, triggerResponse);
};
When you need trigger when someting changes you should use the parameter 'payload' in OnQuery function:
public async Task<object> OnQuery(dynamic request, dynamic payload = null)
{
...
}
Next the OnQuery return the value you can call again the js callback in this way:
payload("Notify js callback!");
I hope this can help someone!

RxJS: Observable.webSocket() get access to onopen, onclose…

const ws = Observable.webSocket('ws://…');
ws.subscribe(
message => console.log(message),
error => console.log(error),
() => {},
);
I want to observe my WebSocket connection with RxJS. Reacting to onmessage events by subscribing to the observable works like a charm. But how can I access the onopen event of the WebSocket? And is it possible to trigger the WebSocket .close() method? RxJS is pretty new to me and I did research for hours, but maybe I just don't know the right terms. Thanks in advance.
Looking at the sourcecode of the Websocket there is a config object WebSocketSubjectConfig which contains observables which you can link to different events. You should be able to pass a NextObserver typed object to config value openObserver like so:
const openEvents = new Subject<Event>();
const ws = Observable.webSocket({
url: 'ws://…',
openObserver: openEvents
});
openEvents
.do(evt => console.log('got open event: ' + evt))
.merge(ws.do(msg => console.log('got message: ' + msg))
.subscribe();
The link of #Mark van Straten to the file is dead. The updated link is here. I also wanted to highlight the usage as suggested in the docs. A in my opinion better copy and paste solution to play around with:
import { webSocket } from "rxjs/webSocket";
webSocket({
url: "wss://echo.websocket.org",
openObserver: {
next: () => {
console.log("connection ok");
},
},
closeObserver: {
next(closeEvent) {
// ...
}
},
}).subscribe();

aurelia aurelia-http-client jsonp

I try to query an api which is not the same origin with the aurelia-http-client.
My code pretty simple :
import {HttpClient} from 'aurelia-http-client';
export class App {
constructor(){
console.log("constructor called");
let url = 'http://localhost:8081/all';
let client = new HttpClient();
client
.jsonp(url)
.then(data => {
console.log("datas");
console.log(data);
});
}
}
Nothing happens, I can see in network that the url is called, my api engine logs an entry but I never enter in the "then" of the "promise"...
What's wrong ?
Update :
I give you some screenshots with catch
code source
browser result
With JQuery on the same machine no problems.
After reading this post other jsonp case I try to add the work "callback" and now it works !!!
so call jsonp(url, 'callback')
client.jsonp(url, 'callback')
Thanks...
This may not be a direct answer but just a suggestion, I would rather use the aurelia API as I found it more consistent and stable.
just add it as plugin in you main :
.plugin('aurelia-api', config => {
config.registerEndpoint('github', 'https://api.github.com/');
});
and use it as:
import {Endpoint} from 'aurelia-api':
#autoinject
export class Users{
constructor(private githubEndpoint){
}
activate() {
return this.githubEndpoint.find('users')
.then(users => this.users = users);
}
}
Source: https://aurelia-api.spoonx.org/Quick%20start.html

jasmine: Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL

I have an angular service called requestNotificationChannel:
app.factory("requestNotificationChannel", function($rootScope) {
var _DELETE_MESSAGE_ = "_DELETE_MESSAGE_";
function deleteMessage(id, index) {
$rootScope.$broadcast(_DELETE_MESSAGE_, { id: id, index: index });
};
return {
deleteMessage: deleteMessage
};
});
I am trying to unit test this service using jasmine:
"use strict";
describe("Request Notification Channel", function() {
var requestNotificationChannel, rootScope, scope;
beforeEach(function(_requestNotificationChannel_) {
module("messageAppModule");
inject(function($injector, _requestNotificationChannel_) {
rootScope = $injector.get("$rootScope");
scope = rootScope.$new();
requestNotificationChannel = _requestNotificationChannel_;
})
spyOn(rootScope, '$broadcast');
});
it("should broadcast delete message notification", function(done) {
requestNotificationChannel.deleteMessage(1, 4);
expect(rootScope.$broadcast).toHaveBeenCalledWith("_DELETE_MESSAGE_", { id: 1, index: 4 });
done();
});
});
I read about the Asynchronous Support in Jasmine, but as I am rather new to unit testing with javascript couldn't make it work.
I am receiving an error :
Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL
and my test is taking too long to execute (about 5s).
Can somebody help me providing working example of my code with some explanation?
Having an argument in your it function (done in the code below) will cause Jasmine to attempt an async call.
//this block signature will trigger async behavior.
it("should work", function(done){
//...
});
//this block signature will run synchronously
it("should work", function(){
//...
});
It doesn't make a difference what the done argument is named, its existence is all that matters. I ran into this issue from too much copy/pasta.
The Jasmine Asynchronous Support docs note that argument (named done above) is a callback that can be called to let Jasmine know when an asynchronous function is complete. If you never call it, Jasmine will never know your test is done and will eventually timeout.
Even for async tests, there is a timeout that goes off in this cases, You can work around this error by increasing the value for the limit timeout to evaluate an async Jasmine callback
describe('Helper', function () {
var originalTimeout;
beforeEach(function() {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000000;
});
afterEach(function() {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
});
it('Template advance', function(doneFn) {
$.ajax({
url: 'public/your-end-point.mock.json',
dataType: 'json',
success: function (data, response) {
// Here your expected using data
expect(1).toBe(1)
doneFn();
},
error: function (data, response) {
// Here your expected using data
expect(1).toBe(1)
doneFn();
}
});
});
});
Source: http://jasmine.github.io/2.0/introduction.html#section-42
This error can also be caused by leaving out inject when initializing a service/factory or whatever. For example, it can be thrown by doing this:
var service;
beforeEach(function(_TestService_) {
service = _TestService_;
});
To fix it just wrap the function with inject to properly retrieve the service:
var service;
beforeEach(inject(function(_TestService_) {
service = _TestService_;
}));
import { fakeAsync, ComponentFixture, TestBed } from '#angular/core/testing';
use fakeAsync
beforeEach(fakeAsync (() => {
//your code
}));
describe('Intilalize', () => {
it('should have a defined component', fakeAsync(() => {
createComponent();
expect(_AddComponent.ngOnInit).toBeDefined();
}));
});
You can use karma-jasmine plugin to set the default time out interval globally.
Add this config in karma.conf.js
module.exports = function(config) {
config.set({
client: {
jasmine: {
timeoutInterval: 10000
}
}
})
}
This error started out of the blue for me, on a test that had always worked. I couldn't find any suggestions that helped until I noticed my Macbook was running sluggishly. I noticed the CPU was pegged by another process, which I killed. The Jasmine async error disappeared and my tests are fine once again.
Don't ask me why, I don't know. But in my circumstance it seemed to be a lack of system resources at fault.
This is more of an observation than an answer, but it may help others who were as frustrated as I was.
I kept getting this error from two tests in my suite. I thought I had simply broken the tests with the refactoring I was doing, so after backing out changes didn't work, I reverted to earlier code, twice (two revisions back) thinking it'd get rid of the error. Doing so changed nothing. I chased my tail all day yesterday, and part of this morning without resolving the issue.
I got frustrated and checked out the code onto a laptop this morning. Ran the entire test suite (about 180 tests), no errors. So the errors were never in the code or tests. Went back to my dev box and rebooted it to clear anything in memory that might have been causing the issue. No change, same errors on the same two tests. So I deleted the directory from my machine, and checked it back out. Voila! No errors.
No idea what caused it, or how to fix it, but deleting the working directory and checking it back out fixed whatever it was.
Hope this helps someone.
You also get this error when expecting something in the beforeAll function!
describe('...', function () {
beforeAll(function () {
...
expect(element(by.css('[id="title"]')).isDisplayed()).toBe(true);
});
it('should successfully ...', function () {
}
}
Don't use done, just leave the function call empty.
It looks like the test is waiting for some callback that never comes. It's likely because the test is not executed with asynchronous behavior.
First, see if just using fakeAsync in your "it" scenario:
it('should do something', fakeAsync(() => {
You can also use flush() to wait for the microTask queue to finish or tick() to wait a specified amount of time.
In my case, this error was caused by improper use of "fixture.detectChanges()" It seems this method is an event listener (async) which will only respond a callback when changes are detected. If no changes are detected it will not invoke the callback, resulting in a timeout error. Hope this helps :)
Works after removing the scope reference and the function arguments:
"use strict";
describe("Request Notification Channel", function() {
var requestNotificationChannel, rootScope;
beforeEach(function() {
module("messageAppModule");
inject(function($injector, _requestNotificationChannel_) {
rootScope = $injector.get("$rootScope");
requestNotificationChannel = _requestNotificationChannel_;
})
spyOn(rootScope, "$broadcast");
});
it("should broadcast delete message notification with provided params", function() {
requestNotificationChannel.deleteMessage(1, 4);
expect(rootScope.$broadcast).toHaveBeenCalledWith("_DELETE_MESSAGE_", { id: 1, index: 4} );
});
});
What I did was: Added/Updated the following code:
framework: 'jasmine',
jasmineNodeOpts:
{
// Jasmine default timeout
defaultTimeoutInterval: 60000,
expectationResultHandler(passed, assertion)
{
// do something
},
}
As noted by #mastablasta, but also to add that if you call the 'done' argument or rather name it completed you just call the callback completed() in your test when it's done.
// this block signature will trigger async behavior.
it("should work", function(done){
// do stuff and then call done...
done();
});
// this block signature will run synchronously
it("should work", function(){
//...
});
jasmine.DEFAULT_TIMEOUT_INTERVAL = 100000;
Keeping this in the block solved my issue.
it('', () => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 100000;
});
Instead of
beforeEach(() => {..
use
beforeEach(fakeAsync(() => {..
In my case, a timeout was cause because of a failed injection of a service with providedIn: 'root'. It's not clear why injection failed, nor why there was no early error if there is apparently no instance of provider available.
I was able to work around it by manually providing a value:
TestBed.configureTestingModule({
declarations: [
// ...
],
imports: [
// ...
],
providers: [
// ...
{ provide: MyService, useValue: { /* ... */ } },
]
}).compileComponents();
I have caught the same error because I used the setTimeout function in the component. Example:
ngOnInit(): void {
this.changeState();
}
private changeState(): void {
setTimeout(() => this.state = StateEnum.IN_PROGRESS, 10000);
}
When I changed the timeout from 10000ms to 0 or less than 5000ms (DEFAULT_TIMEOUT_INTERVAL), all tests were passed.
In my case, I was not returning the value from the spy method, hence facing error,
mainMethod(args): Observable<something>{
return nestedMethod().pipe();
}
Your Test should like below,
it('your test case', (done: DoneFn) => {
const testData = {}; // Your data
spyOn(service, 'nestedMethod').and.returnValue(of(testData));
const obxValue = service.mainMethod('your args');
obxValue.pipe(first()).subscribe((data) => {
expect(data).not.toBeUndefined();
done();
});
});
If you have an argument (done) in the it function try to remove it as well it's call within the function itself:
it("should broadcast delete message notification", function(/*done -> YOU SHOULD REMOVE IT */) {
requestNotificationChannel.deleteMessage(1, 4);
expect(rootScope.$broadcast).toHaveBeenCalledWith("_DELETE_MESSAGE_", { id: 1, index: 4 });
// done(); -> YOU SHOULD REMOVE IT
});

Categories

Resources