I have the following code:
$scope.deleteJob = function(job) {
SandboxService.deleteJob(job.id).then(res => {
if (res.status == 200) {
ngToast.success();
$scope.refreshApps();
}
else {
ngToast.danger();
}
});
};
And the following unit test:
it('should show success toast on delete and refresh apps', () => {
spyOn(sandboxService, 'deleteJob').and.returnValue(Promise.resolve({status: 500}));
spyOn(ngToast, 'success');
spyOn(scope, 'refreshApps');
let mockJob = {
'id': 1
};
scope.deleteJob(mockJob);
sandboxService.deleteJob().then(() => {
expect(ngToast.success).toHaveBeenCalled();
expect(scope.refreshApps).toHaveBeenCalled();
});
});
Basically when deleting a job, if the delete was a success with a returned status of 200 then show a success toast and refresh, else show a danger toast.
I expect the test to fail, as it returns a status of 500, but it passes. This implies that ngToast.success() and scope.refreshApps() have been called.
I added some logs to the code, and it does return status: 500 and go to the else block.
What am I missing here?
The problem is related to the asynchronous nature of deleteJob. Your it test ends even before expect is performed. Therefore you need some sort of synchronization. This could basically be done with fakeAsync and tick from #angular/core/testing.
it('should show success toast on delete and refresh apps', fakeAsync(() => {
...
sandboxService.deleteJob();
tick();
expect(ngToast.success).toHaveBeenCalled();
expect(scope.refreshApps).toHaveBeenCalled();
}));
The problem however is that you're overwriting the original behaviour of deleteJob with the spy below, hence ngToast.success and scope.refreshApps won't be called and the test will fail.
spyOn(sandboxService, 'deleteJob').and.returnValue(Promise.resolve({status: 500}));
#uminder's answer pointed out that the test was finishing before the expect functions were even called due the asynchronous nature - verified by adding some logs inside the test.
The solution was to add an argument to the test that is to be called when the test has finished: https://jasmine.github.io/2.0/introduction.html#section-Asynchronous_Support
it('should show success toast on delete and refresh apps', (done) => {
spyOn(sandboxService, 'deleteJob').and.returnValue(Promise.resolve({status: 200}));
spyOn(ngToast, 'success');
spyOn(scope, 'refreshApps');
let mockJob = {
'id': 1
};
scope.deleteJob(mockJob);
sandboxService.deleteJob().then(() => {
expect(ngToast.success).toHaveBeenCalled();
expect(scope.refreshApps).toHaveBeenCalled();
done();
});
});
Related
So I have this nuxt page /pages/:id.
In there, I do load the page content with:
content: function(){
return this.$store.state.pages.find(p => p.id === this.$route.params.id)
},
subcontent: function() {
return this.content.subcontent;
}
But I also have an action in this page to delete it. When the user clicks this button, I need to:
call the server and update the state with the result
redirect to the index: /pages
// 1
const serverCall = async () => {
const remainingPages = await mutateApi({
name: 'deletePage',
params: {id}
});
this.$store.dispatch('applications/updateState', remainingPages)
}
// 2
const redirect = () => {
this.$router.push({
path: '/pages'
});
}
Those two actions happen concurrently and I can't orchestrate those correctly:
I get an error TypeError: Cannot read property 'subcontent' of undefined, which means that the page properties are recalculated before the redirect actually happens.
I tried:
await server call then redirect
set a beforeUpdate() in the component hooks to handle redirect if this.content is empty.
delay of 0ms the server call and redirecting first
subcontent: function() {
if (!this.content.subcontent) return redirect();
return this.content.subcontent;
}
None of those worked. In all cases the current page components are recalculated first.
What worked is:
redirect();
setTimeout(() => {
serverCall();
}, 1000);
But it is obviously ugly.
Can anyone help on this?
As you hinted, using a timeout is not a good practice since you don't know how long it will take for the page to be destroyed, and thus you don't know which event will be executed first by the javascript event loop.
A good practice would be to dynamically register a 'destroyed' hook to your page, like so:
methods: {
deletePage() {
this.$once('hook:destroyed', serverCall)
redirect()
},
},
Note: you can also use the 'beforeDestroy' hook and it should work equally fine.
This is the sequence of events occurring:
serverCall() dispatches an update, modifying $store.state.pages.
content (which depends on $store.state.pages) recomputes, but $route.params.id is equal to the ID of the page just deleted, so Array.prototype.find() returns undefined.
subcontent (which depends on content) recomputes, and dereferences the undefined.
One solution is to check for the undefined before dereferencing:
export default {
computed: {
content() {...},
subcontent() {
return this.content?.subcontent
👆
// OR
return this.content && this.content.subcontent
}
}
}
demo
I'm trying to provide a fallback for the failed ajax requests.
I want a global solution so I won't have to change every call in the code.
I tried providing an error handler to ajaxSetup, but the problem is I couldn't execute the chained callbacks.
$.ajaxSetup({
error: function() {
console.error('Error occurred')
return $.getJSON('https://jsonplaceholder.typicode.com/todos/1')
}
})
$.getJSON('https://jsonplaceholder.typicode.com/todos/0') // Id doesn't exist
.then(todo => console.log(todo))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Expected output
Error occurred
{
"id": 1,
"title": "...",
...
}
From jQuery 3.0 the callback method accepted are: done, always, fail.
So, i would have called the callback fail and in the inner, i resend the ajax call wrapped into a properly function with dynamic id
const submit = (id) => {
const xhr = $.getJSON(`https://jsonplaceholder.typicode.com/todos/${id}`)
.done(todo => console.log(todo))
.fail(err => { console.error(err); submit(id++); });
};
submit(0);
I have written the following code, it runs smoothly but I have encountered a question:
submitFormToBackend = async () => {
if (this.paymentMethod === 'apple-pay') {
this.setState({ showLoadingIndicator: true }); // <-- below await setTimeout can confirm this line run before it
}
let requester = new ApplePayRequester({...this.form});
let applePay = new ApplePay();
await setTimeout(async () => {
let cardTokenResponse = await applePay.getCardToken();
if (cardTokenResponse.isSuccess()) {
requester.setCardToken(cardTokenResponse.message);
let response = await requester.pushToBackend();
this.setState({ showLoadingIndicator: false }); //<-- below setTimeout can confirm this line run before them
if (response.isSuccess()) {
setTimeout(() => { this.navigator.backToPreviousScreen(); }, 800);
} else {
setTimeout(() => { Alert.alert('your purchase has error. Try again'); }, 800);
}
} else {
this.setState({ showLoadingIndicator: false });
setTimeout(() => { Alert.alert('cannot get your card token.'); }, 800);
}
}, 800);
};
My render() in that component:
render() {
return (
<View style={styles.form}>
<LoadingIndicator visible={this.state.showLoadingShader} />
<InputBox />
<InputBox />
<SubmitButton />
</View>
);
}
As you see there are a lot of setTimeout() functions, it seems like functions will crash together if I don't use setTimeout() to restrict the functions run one by one.
However, it's not a good practice as there is no default millisecond for success running (the millisecond can set to 700ms or 1500ms or etc.). Therefore I would like to ask is there any solution to confirm previous function has run before next function start, other than using setTimeout()?
UPDATE
Procedures:
Step 1 - Press submit button
Step 2 - Pop up a confirmation modal
Step 3 - User confirm, dismiss confirmation modal, set showLoadingIndicator to true to show loading indicator
Step 4 - Call ApplePay and pop up ApplePay UI
Step 5 - User confirm, set showLoadingIndicator to false to dismiss loading indicator and navigate previous screen
Problems encountered when not using setTimeout():
Step 4 - ApplePay UI cannot pop up after setting showLoadingIndicator to true, below is the code that encountered problem:
let cardTokenResponse = await applePay.getCardToken();
Step 5 - Alert will be pop up before setting showLoadingIndicator to false, which stops the setting, below is the code that encountered problem:
this.setState({ showLoadingIndicator: false });
if (response.isSuccess()) {
} else {
setTimeout(() => { Alert.alert('your purchase has error. Try again'); }, 800);
}
A second optional parameter of setState function is a callback function that runs synchronously with the state change.
So you can just rely on the following:
this.setState({
//change state variables here
}, () => {
//do the next work here...
});
The callback function always run post the state is changed.
In your code, this would work:
this.setState({ showLoadingIndicator: false }, () => {
if (response.isSuccess()) {
this.navigator.backToPreviousScreen();
} else {
Alert.alert('your purchase has error. Try again');
}
});
I am trying to transition the script from one state to another based on Smooch postback payloads; but getting error code H12.
Consider the example https://github.com/smooch/smooch-bot-example
Say I modify the script https://github.com/smooch/smooch-bot-example/blob/master/script.js as follows
start: {
receive: (bot) => {
return bot.say('Hi! I\'m Smooch Bot! Continue? %[Yes](postback:askName) %[No](postback:bye) );
}
},
bye: {
prompt: (bot) => bot.say('Pleasure meeting you'),
receive: () => 'processing'
},
The intention is that the's bot's state would transition depending on the postback payload.
Question is, how do I make that happen?
My approach was add
stateMachine.setState(postback.action.payload)
to the handlePostback method of github.com/smooch/smooch-bot-example/blob/master/heroku/index.js
However, that threw an error code H12. I also experimented with
stateMachine.transition(postback.action,postback.action.payload)
to no avail.
I got the same issue with the [object Object] instead of a string. This is because the state you get or set with a function is contained in an object, not a string... I fixed it with this code inside index.js, replacing the existing handlePostback function in the smooch-bot-example GitHub repo:
function handlePostback(req, res) {
const stateMachine = new StateMachine({
script,
bot: createBot(req.body.appUser)
});
const postback = req.body.postbacks[0];
if (!postback || !postback.action) {
res.end();
};
const smoochPayload = postback.action.payload;
// Change conversation state according to postback clicked
switch (smoochPayload) {
case "POSTBACK-PAYLOAD":
Promise.all([
stateMachine.bot.releaseLock(),
stateMachine.setState(smoochPayload), // set new state
stateMachine.prompt(smoochPayload) // call state prompt() if any
]);
res.end();
break;
default:
stateMachine.bot.say("POSTBACK ISN'T RECOGNIZED") // for testing purposes
.then(() => res.end());
};
}
Then inside script.js all you need to do is define states corresponding to the exact postback payloads. If you have multiple postbacks that should take the user to other states, just add them to the case list like so :
case "POSTBACK-PAYLOAD-1":
case "POSTBACK-PAYLOAD-2":
case "POSTBACK-PAYLOAD-3":
case "POSTBACK-PAYLOAD-4":
Promise.all([
stateMachine.bot.releaseLock(),
stateMachine.setState(smoochPayload), // set new state
stateMachine.prompt(smoochPayload) // call state prompt() if any
]);
res.end();
break;
Note that you should not write break; at the end of each case if the outcome you want is the same (here : setting the state and prompting the corresponding message).
If you want to handle other postbacks differently, you can add cases after the break; statement and do other stuff instead.
Hope this helps!
Postbacks won't automatically transition your conversation from one state to the next, you have to write that logic yourself. Luckily the smooch-bot-example you're using already has a postback handler defined here:
https://github.com/smooch/smooch-bot-example/blob/30d2fc6/heroku/index.js#L115
So whatever transition logic you want should go in there. You can do this by creating a stateMachine and calling receiveMessage() on it the same way handleMessages() already works. For example:
const stateMachine = new StateMachine({
script,
bot: createBot(req.body.appUser)
});
stateMachine.receiveMessage({
text: 'whatever your script expects'
})
Alternatively, you could have your handlePostback implementation call stateMachine.setState(state) and stateMachine.prompt(state) independently, if you wanted to have your postbacks behave differently from regular text responses.
If you want to advance the conversation based on a postback you'll have to first output the buttons from the bot's prompt (so you can handle the button click in the receive), modify the handlePostback function in index.js, then handle the user's "reply" in your receive method - try this - modify script.js like so:
start: {
prompt: (bot) => bot.say(`Hi! I'm Smooch Bot! Continue? %[Yes](postback:askName) %[No](postback:bye)`),
receive: (bot, message) => {
switch(message.text) {
case 'Yes':
return bot.say(`Ok, great!`)
.then(() => 'hi')
break;
case 'No':
return bot.say(`Ok, no prob!`)
.then(() => 'bye')
break;
default:
return bot.say(`hmm...`)
.then(() => 'processing')
break;
}
}
},
hi: {
prompt: (bot) => bot.say('Pleasure meeting you'),
receive: () => 'processing'
},
bye: {
prompt: (bot) => bot.say('Pleasure meeting you'),
receive: () => 'processing'
},
Then modify the handlePostback function in index.js so that it treats a postback like a regular message:
function handlePostback(req, res) {
const postback = req.body.postbacks[0];
if (!postback || !postback.action)
res.end();
const stateMachine = new StateMachine({
script,
bot: createBot(req.body.appUser)
});
const msg = postback;
// if you want the payload instead just do msg.action.paylod
msg.text = msg.action.text;
stateMachine.receiveMessage(msg)
.then(() => res.end())
.catch((err) => {
console.error('SmoochBot error:', err);
res.end();
});
}
Now when a user clicks your button it will be pushed to the stateMachine and handled like a reply.
I am trying to spy on $.ajax in Jasmine 2.0 tests. Here is a simplified example (TypeScript) showing my scenario:
describe("first test", () => {
var deferred = jQuery.Deferred();
spyOn($, "ajax").and.callFake((uri: string, settings: JQueryAjaxSettings) => {
return deferred.resolve("ThisIsADummyResult");
});
it("should return dummy result", done => {
$.ajax("http://somedummyserver.net").then(result => {
expect(result).toBe("ThisIsADummyResult");
done();
});
});
});
describe("second test", () => {
var deferred = jQuery.Deferred();
spyOn($, "ajax").and.callFake((uri: string, settings: JQueryAjaxSettings) => {
return deferred.resolve("ThisIsAnotherResult");
});
it("should return another result", done => {
$.ajax("http://somedummyserver.net").then(result => {
expect(result).toBe("ThisIsAnotherResult");
done();
});
});
});
firstTest as well as second test work if I run them alone. However, if I run both tests as shown above, I get the following error message: ajax has already been spied upon.
So my questions are:
Shouldn't the spies be reset by Jasmine after each test automatically? Why doesn't that work in my case?
Is there another way of using spyOn which makes Jasmine reset the spies?
How can I manually reset the spies?
Update: I continued experimenting and found a possible solution myself. If I set up the spies inside of the it spec, both tests run fine. Here is the code for first test showing what I mean:
describe("first test", () => {
it("should return dummy result", done => {
var deferred = jQuery.Deferred();
spyOn($, "ajax").and.callFake((uri: string, settings: JQueryAjaxSettings) => {
return deferred.resolve("ThisIsADummyResult");
});
$.ajax("http://somedummyserver.net").then(result => {
expect(result).toBe("ThisIsADummyResult");
done();
});
});
});
Still, it would be very interesting why the first version does not work. Why does Jasmine not reset the spies in the first version whereas it does in the second one?
For stuff that is used across all tests but you need it reset for each test use 'beforeEach' : http://jasmine.github.io/2.0/introduction.html#section-Setup_and_Teardown
Jasmine does not magically know which lines of your describe body you want reevaluated for each 'it' block.