Keep "this" in bootbox callback functions - vue.js

I'm trying to keep this variable in the callback:
var that = this
// type1
bootbox.confirm("This is the default confirm!", function(result){
console.log(that.whatever);
});
// type2
bootbox.confirm({
message: "This is a confirm with custom button text and color! Do you like it?",
callback: function (result) {
console.log(that.whatever);
}
});
It looks ugly, is there any better way to do it?

You can use an arrow function:
bootbox.confirm("This is the default confirm!", result => {
console.log(this.whatever);
});
You should compile this with Babel though, older browsers may not support it. If you have the callback as a variable, you can bind it before passing:
yourCb.bind(this);
bootbox.confirm("This is the default confirm!", yourCb);

Related

vue-test-utils | TypeError: s.split is not a function

I try to run a test with vue-test-utils, including a component that has a mixin included, which has a function using split() on a string. The test looks like this:
describe('adminExample.vue Test', () => {
const wrapper = shallowMount(adminExample, {
global: {
mixins: [globalHelpers, authGatewayForElements, storeService],
plugins: [store]
}
})
it('renders component and is named properly', () => {
// check the name of the component
expect(wrapper.vm.$options.name).toMatch('adminExample')
})
})
adminExample.vue doesn't give any error, so I don't include it here, bit it uses a mixin.
The included mixin, called authGatewayForElements, has a function called decryptToken() and simply decrypt a jwt to get some info. The parameter userToken is declared within data of this mixin. The function looks like this:
decryptToken() {
let base64Split = this.userToken.split('.')[1];
let base64 = base64Split.replace(/-/g, '+').replace(/_/g, '/');
let jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
},
Running the test giving me the error TypeError: this.userToken.split is not a function . I´m new to testing with vue-test-utils and maybe or definitely missing something that needs to beincluded in the wrapper, as I expected functions like split() don't need to be included additionally.
EDIT: I get this error on multiple functions, like find(), so I'm pretty sure I just do something wrong. Thanks in advance to anybody pointing that out.

Event only firing as inline JS statement

I have the following code in a Nuxtjs app in SSR mode.
<Component
:is="author.linkUrl ? 'a' : 'div'"
v-bind="!author.linkUrl && { href: author.linkUrl, target: '_blank' }"
#click="author.linkUrl ? handleAnalytics() : null"
>
The click event in case it's an a tag, will only fire if it's written as handleAnalytics(), but handleAnalytics will not work.
Don't get me wrong the code is working, but I don't understand why.
With classical event binding (#click="handleAnalytics), Vue will auto bind it for you because it sees it's a function.
But when provided a ternary condition, it's not auto binded but wrapped into a anonymous function instead. So you have to call it with parenthesis otherwise you're just returning the function without executing it.
To be clearer, you can write it this way: #click="() => author.linkUrl ? handleAnalytics() : null"
Note: when having a dynamic tag component, I'd suggest to use the render function instead.
This is an advanced technique, but this way you won't bind things to an element that doesn't need it (without having the kind of hack to return null).
Example:
export default {
props: {
author: { type: Object, required: true },
},
render (h: CreateElement) {
const renderLink = () => {
return h('a', {
attrs: {
href: author.linkUrl,
target: '_blank',
},
on: {
click: this.handleAnalytics
},
)
}
const renderDiv = () => {
return h('div')
}
return this.author.linkUrl ? renderLink() : renderDiv()
}
}
Documention: Vue2, Vue3
In javascript functions are a reference to an object. Just like in any other language you need to store this reference in memory.
Here are a few examples that might help you understand on why its not working:
function handleAnalytics() { return 'bar' };
const resultFromFunction = handleAnalytics();
const referenceFn = handleAnalytics;
resultFromFunction will have bar as it's value, while referenceFn will have the reference to the function handleAnalytics allowing you to do things like:
if (someCondition) {
referenceFn();
}
A more practical example:
function callEuropeanUnionServers() { ... }
function callAmericanServers() { ... }
// Where would the user like for his data to be stored
const callAPI = user.preferesDataIn === 'europe'
? callEuropeanUnionServers
: callEuropeanUnionServers;
// do some logic
// ...
// In this state you won't care which servers the data is stored.
// You will only care that you need to make a request to store the user data.
callAPI();
In your example what happens is that you are doing:
#click="author.linkUrl ? handleAnalytics() : null"
What happens in pseudo code is:
Check the author has a linkUrl
If yes, then EXECUTE handleAnalytics first and then the result of it pass to handler #click
If not, simply pass null
Why it works when you use handleAnalytics and not handleAnalytics()?
Check the author has a linkUrl
If yes, then pass the REFERENCE handleAnalytics to handler #click
If not, simply pass null
Summary
When using handleAnalytics you are passing a reference to #click. When using handleAnalytics() you are passing the result returned from handleAnalytics to #click handler.

how to use dynamic assertion method name?

Let's say I have this in a test:
await t.expect(Selector('input')).ok()
And I would like to have (something like) this:
let func = 'ok';
await t.expect(Selector('input'))[func]()
This is so that I can have a map from selector to function, in order to iterate
over it and check whether some elements are in the page (ok) and some not (notOk).
My above attempt does not work and returns with an interesting error:
code: 'E1035',
data: [
'SyntaxError: test.js: await is a reserved word (325:14)'
]
I believe this is because Testcafe is doing some magic under the hood.
What would be the correct syntax to make it work?
It seems that you skipped the Selector property that you want to check (e.g. exists, visible, textContent, etc.). The following test example works properly with TestCafe v1.14.2:
import { Selector } from 'testcafe';
fixture`A set of examples that illustrate how to use TestCafe API`
.page`http://devexpress.github.io/testcafe/example/`;
const developerName = Selector('#developer-name');
const submitButton = Selector('#submit-button');
test('New Test', async t => {
await t
.typeText(developerName, 'Peter Parker')
.click(submitButton);
let assertFunc = 'ok';
await t.expect(Selector('#article-header').exists)[assertFunc]();
});

Testing model binding in Backbone JS with Jasmine

I have a view that contains a model. The view listens for an event from the model and will perform an action once the event is triggered. Below is my code
window.Category = Backbone.Model.extend({})
window.notesDialog = Backbone.View.extend({
initialize: function() {
this.model.bind("notesFetched", this.showNotes, this);
},
showNotes: function(notes) {
//do stuffs here
}
})
I want to test this using Jasmine and below is my test (which doesn't work)
it("should show notes", function() {
var category = new Category;
var notes_dialog = new NotesDialog({model: category})
spyOn(notes_dialog, "showNotes");
category.trigger("notesFetched", "[]");
expect(notes_dialog.showNotes).toHaveBeenCalledWith("[]");
})
Does anyone know why the above test doesn't work? The error I get is "Expected spy showNotes to have been called with [ '[]' ] but it was never called."
I was doing something similar where I had a view, but I couldn't get the spy to work properly unless I added it to the prototype, and before I created the instance of the view.
Here's what eventually worked for me:
view.js
view = Backbone.View.extend({
initialize: function(){
this.collection.bind("change", this.onChange, this);
},
...
onChange: function(){
console.log("Called...");
}
});
jasmine_spec.js
describe("Test Event", function(){
it("Should spy on change event", function(){
var spy = spyOn(view.prototype, 'onChange').andCallThrough()
var v = new view( {collection: some_collection });
// Trigger the change event
some_collection.set();
expect(spy).toHaveBeenCalled()
});
});
I would test initially with the toHaveBeenCalled() expectation and change to the toHaveBeenCalledWith() after you get that working...
Update 5/6/2013: Changed update() to set()
Try to amend your existing test code as follows:
it("should show notes", function() {
var category = new Category;
spyOn(NotesDialog.prototype, "showNotes");
var notes_dialog = new NotesDialog({model: category})
category.trigger("notesFetched", "[]");
expect(notes_dialog.showNotes).toHaveBeenCalledWith("[]");
})
In your original code, the instance of the method you are calling is one defined in the bind closure, whereas the one you are spying on is in the notes_dialog instance. By moving the spy to the prototype, you are replacing it before the bind takes place, and therefore the bind closure encapsulates the spy, not the original method.
Using a spy means to replace the function you spying on. So in your case you replace the bind function with the spy, so the internal logic of the original spy will not call anymore. And thats the right way to go cause you dont wanna test that Backbones bind is work but that you have called bind with the specific paramaters "notesFetched", this.showNotes, this.
So how to test this. As you know every spy has the toHaveBeenCalledWith(arguments) method. In your case it should looks like this:
expect(category.bind).toHaveBeenCalledWith("notesFetched", category. showNotes, showNotes)
So how to test that trigger the "notesFetched" on the model will call your showNotes function.
Every spy saves the all parameters he was called with. You can access the last one with mostRecentCall.args.
category.bind.mostRecentCall.args[1].call(category.bind.mostRecentCall.args[2], "[]");
expect(notes_dialog.showNotes).toHaveBeenCalledWith("[]");
mostRecentCall.args[1] is the the second argument in your bind call (this.showNotes). mostRecentCall.args[2] is the the third argument in your bind call (this).
As we have test that bind was called with your public method showNotes, you can also call the your public method showNotes directly, but sometimes the passed arguments can access from outside so you will use the shown way.
Your code looks fine, except do you have the test wrapped in a describe function, as well as an it function?
describe("show notes", function(){
it("should show notes", function(){
// ... everything you already have here
});
});
Total guess at this point, but since you're not showing the describe function that's all I can think it would be. You must have a describe block for the tests to work, if you don't have one.
You are pretty close ;)
spyOn replaces the function with your spy and returns you the spy.
So if you do:
var dialog_spy = spyOn(notes_dialog, "showNotes");
category.trigger("notesFetched", "[]");
expect(dialog_spy).toHaveBeenCalledWith("[]");
should work just fine!

How to register an event handler on a plugin in YUI3

Given the code below, is there a better way to register an event handler on the resize plugin? Thanks!
var target = Y.Node.create('<div class="rich-text-container"></div>');
// ...
target.plug(Y.Plugin.Resize,{
wrap : true
});
target[Y.Plugin.Resize.NS].on('resize:end',function (e) {
debugger;
// This runs, but is there a better way?
});
target.resize.on('resize:end',function (e) {
alert('this is correct');
});
Y.Plugin.Resize.NS points to the string 'resize' and indicates where on the plugin host the plugin instance will be stored. Derp.