Flutter: BLoC, testing streams - testing

Testing the bloc pattern is not so clear to me. So, if I have these 2 stream controllers:
final _controller1 = StreamController();
final _controller2 = StreamController<bool>;
Sink get controller1Add = _controller1.sink;
Stream<bool> get controller2Out = _controller2.stream;
and I want to test that, from this function:
submit() {
if (_controller1.value == null ||
_controller1.value.isEmpty) {
print(...)
return;
}else
_controller2.sink.add(true);
}
the _controller2.stream should have true, how should I do?
I tried something like:
test("test", (){
bloc.submit();
expect(bloc.controller2Out, emitsAnyOf([true]));
});
but, of course, it didn´t work.

I've modified your code to use the RxDart's BehaviorSubject and it seems to work. You are using StreamController but I get error cause it doesn't have the value property.
final _controller1 = BehaviorSubject<String>();
final _controller2 = BehaviorSubject<bool>();
Sink get controller1Add => _controller1.sink;
Stream<bool> get controller2Out => _controller2.stream;
submit() {
if (_controller1.value == null || _controller1.value.isEmpty) {
print('Error');
_controller2.sink.add(false);
return;
} else {
print('OK');
_controller2.sink.add(true);
}
}
The test:
bloc.controller1Add.add('');
bloc.submit();
expect(bloc.controller2Out, emits(false));
bloc.controller1Add.add('test');
bloc.submit();
expect(bloc.controller2Out, emits(true));
bloc.controller1Add.add('');
bloc.submit();
expect(bloc.controller2Out, emits(false));

Related

How can I refresh datatable in Wire using refreshApex

#wire(_getContacts,{recordId:'$recordId'}) wiredContacts({error,data}){
this.dataToRefresh = data;
if (data) {
this.contacts = this.dataToRefresh.recordList;
this.ContactsRecords = this.dataToRefresh.cList;
this.contactsSize = " Case Contacts (" + this.contacts.length + ")";
}else{
//
}
};
relateContacts() {
this.showSpinner = true;
this.showtable=false;
relateContacts({contacts: this.selected, recordId: this.recordId})
.then(data => {
this.showSpinner=false;
this.showtable=true;
this.showSuccessMessage();
refreshApex(this.dataToRefresh);
//location.reload();
this.isShowModal = false;
})
.catch(error => {
console.log(error);
this.showSpinner=false;
const evt = new ShowToastEvent({
title: 'Application Error',
message: error.body.message,
variant: 'error',
mode: 'sticky'
});
this.dispatchEvent(evt);
this.showSpinner = false;
});
}
For this code, I tried refreshApex with all possible ways. but I'm not sure the miss here. I've Checked all the blogs but everywhere, the solution is mentioned.
Tried refreshApex like below :
#wire(_getContacts,{recordId:'$recordId'}) wiredContacts({data}){
this.dataToRefresh = data;
But this also does not work
Ah that is a fun one ! Your issue is using destructuring in wiredContacts as the parameter.
(The {data} or {data,error} normally works as a parameter to the function being called back, except if you have to do refresh) Try this instead.
#wire(_getContacts,{recordId:'$recordId'}) wiredContacts(value){
this.dataToRefresh = value;
const {data, error} = value;
//Rest of you code now with data and error
}
Then in your other method you can do:
method(){
refreshApex(this.dataToRefresh);
}
Salesforce does show doing this in their example code, but it’s easy to miss and experience the fun you have been having with this.
https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.apex_result_caching
See the last example on their page.

Is there a way to wait until a function is finished in React Native?

I'm trying to get information (true/false) from AsyncStorage in a function and create a string which is importent to fetch data in the next step. My problem is, the function is not finished until the string is required.
I tried many solutions from the internet like async function and await getItem or .done() or .then(), but none worked out for me.
//_getFetchData()
AsyncStorage.getAllKeys().then((result) => { //get all stored Keys
valuelength = result.length;
if (valuelength !== 0) {
for (let i = 0; i < valuelength; i++) {
if (result[i].includes("not") == false) { //get Keys without not
AsyncStorage.getItem(result[i]).then((resultvalue) => {
if (resultvalue === 'true') {
if (this.state.firstValue) {
this.state.channels = this.state.channels + "channel_id" + result[i];
console.log("channel: " + this.state.channels);
}
else {
this.state.channels = this.state.channels + "channel" + result[i];
}
}
});
}
return this.state.channels;
_fetchData() {
var channel = this._getFetchData();
console.log("channel required: " + channel);
}
The current behaviour is that the console displays first "channel required: " than "channel: channel_id0".
Aspects in your question are unclear:
You don't say when this.state.firstValue is set, and how that relates to what you are trying to accomplish.
You have a for-loop where you could be setting the same value multiple times.
You mutate the state rather than set it. This is not good, see this SO question for more on that.
There are somethings we can do to make your code easier to understand. Below I will show a possible refactor. Explaining what I am doing at each step. I am using async/await because it can lead to much tidier and easier to read code, rather than using promises where you can get lost in callbacks.
Get all the keys from AsyncStorage
Make sure that there is a value for all the keys.
Filter the keys so that we only include the ones that do not contain the string 'not'.
Use a Promise.all, this part is important as it basically gets all the values for each of the keys that we just found and puts them into an array called items
Each object in the items array has a key and a value property.
We then filter the items so that only the ones with a item.value === 'true' remain.
We then filter the items so that only the ones with a item.value !== 'true' remain. (this may be optional it is really dependent on what you want to do)
What do we return? You need to add that part.
Here is the refactor:
_getFetchData = async () => {
let allKeys = await AsyncStorage.getAllKeys(); // 1
if (allKeys.length) { // 2
let filteredKeys = allKeys.filter(key => !key.includes('not')); // 3
let items = await Promise.all(filteredKeys.map(async key => { // 4
let value = await AsyncStorage.getItem(key);
return { key, value }; // 5
}))
let filteredTrueItems = items.filter(item => items.value === 'true'); // 6
let filteredFalseItems = items.filter(item => items.value !== 'true'); // 7
// now you have two arrays one with the items that have the true values
// and one with the items that have the false values
// at this points you can decide what to return as it is not
// that clear from your question
// return the value that your want // 8
} else {
// return your default value if there are no keys // 8
}
}
You would call this function as follows:
_fetchData = async () => {
let channel = await this._getFetchData();
console.log("channel required: " + channel);
}
Although the above will work, it will not currently return a value as you haven't made it clear which value you wish to return. I would suggest you build upon the code that I have written here and update it so that it returns the values that you want.
Further reading
For further reading I would suggest these awesome articles by Michael Chan that discuss state
https://medium.learnreact.com/setstate-is-asynchronous-52ead919a3f0
https://medium.learnreact.com/setstate-takes-a-callback-1f71ad5d2296
https://medium.learnreact.com/setstate-takes-a-function-56eb940f84b6
I would also suggest taking some time to read up about async/await and promises
https://medium.com/#bluepnume/learn-about-promises-before-you-start-using-async-await-eb148164a9c8
And finally this article and SO question on Promise.all are quite good
https://www.taniarascia.com/promise-all-with-async-await/
Using async/await with a forEach loop
Try this instead. Async functions and Promises can be tricky to get right and can be difficult to debug but you're on the right track.
async _getFetchData() {
let channels = "";
let results = await AsyncStorage.getAllKeys();
results.forEach((result) => {
if (result.includes("not") === false) {
let item = await AsyncStorage.getItem(result);
if (item === 'true') {
console.log(`channel: ${result}`)
channels = `channel_id ${result}`;
}
}
});
return channels;
}
_fetchData() {
this._getFetchData().then((channels) => {
console.log(`channel required: ${channel}`);
});
}
what if you wrap the _getFetchData() in a Promise? This would enable you to use
var channel = this._getFetchData().then(console.log("channel required: " + channel));
Otherwise the console.log won't wait for the execution of the _getFetchData().
This is what the console.log is telling you. it just logs the string. the variable is added after the async operation is done.
UPDATE
I would try this:
//_getFetchData()
AsyncStorage.getAllKeys().then((result) => { //get all stored Keys
valuelength = result.length;
if (valuelength !== 0) {
for (let i = 0; i < valuelength; i++) {
if (result[i].includes("not") == false) { //get Keys without not
AsyncStorage.getItem(result[i]).then((resultvalue) => {
if (resultvalue === 'true') {
if (this.state.firstValue) {
this.state.channels = this.state.channels + "channel_id" + result[i];
console.log("channel: " + this.state.channels);
}
else {
this.state.channels = this.state.channels + "channel" + result[i];
}
}
});
}
return new Promise((resolve, reject) => {
this.state.channels !=== undefined ? resolve(this.state.channels) : reject(Error('error '));
}
_fetchData() {
var channel = this._getFetchData().then(console.log("channel required: " + channel));
}
maybe you must change the this.state.channels !=== undefined to an expression that's matches the default value of this.state.channels.

Get JavaScript Array of Objects to bind to .Net Core List of ViewModel

I have a JS Array of Objects which, at time of Post contains three variables per object:
ParticipantId,
Answer,
ScenarioId
During post, there is an Array the size of 8 (at current anyway) which all correctly contain data. When I call post request, the Controller does get hit as the breakpoint triggers, the issue is when I view the List<SurveyResponse> participantScenarios it is shown as having 0 values.
The thing I always struggle to understand is that magic communication and transform between JS and .Net so I am struggling to see where it is going wrong.
My JS Call:
postResponse: function () {
var data = JSON.stringify({ participantScenarios: this.scenarioResponses})
// POST /someUrl
this.$http.post('ScenariosVue/PostScenarioChoices', data).then(response => {
// success callback
}, response => {
// error callback
});
}
My .Net Core Controller
[HttpPost("PostScenarioChoices")]
public async Task<ActionResult> PostScenarioChoices(List<SurveyResponse> participantScenarios)
{
List<ParticipantScenarios> addParticipantScenarios = new List<ParticipantScenarios>();
foreach(var result in participantScenarios)
{
bool temp = false;
if(result.Answer == 1)
{
temp = true;
}
else if (result.Answer == 0)
{
temp = false;
}
else
{
return StatusCode(400);
}
addParticipantScenarios.Add(new ParticipantScenarios
{
ParticipantId = result.ParticipantId,
Answer = temp,
ScenarioId = result.ScenarioId
});
}
try
{
await _context.ParticipantScenarios.AddRangeAsync(addParticipantScenarios);
await _context.SaveChangesAsync();
return StatusCode(201);
}
catch
{
return StatusCode(400);
}
}

Aurelia refresh property dependencies

Validate if checkbox should be displayed in html page:
get canPerformCommand() {
let r = false;
let valids = ['Success', 'Error'];
if (this.requests.length == 0) return false;
if (valids.indexOf(this.myresult[0].requestStatus) > 0) {
r = true;
}
return r;
}
Html page:
<span if.bind="canPerformCommand" class="panel-heading-buttons">
<button click.trigger="confirm()">Confirm</button>
</span>
Search:
return this.myService.getRequests()
.then(data => {
this.requests = data
//Somehow refresh canPerformCommand here?
});
this.requests will be empty on first page load, resulting in canPerformCommand = false.
I want to refresh canPerformCommand when using the search function.
Currently canPerformCommand will not refresh itself after a search has been done.
How do I refresh canPerformCommand after search using Property Dependencies?
Solution:
The easiest and most logical solution would be to change canPerformCommand into two separate entities -- a flag variable and a function. Make the flag variable be canPerformCommand and keep the if.bind=canPerformCommand but change the name of your function to updateCanPerformCommand() so that you can easily call this function from your return this.myService.getRequests() .then function.
Details:
Set up your view-model like this:
export class App { // <-- (or whatever yours is called)
canPerformCommnad = false;
constructor() {
// ...
}
updateCanPerformCommand() {
let r = false;
let valids = ['Success', 'Error'];
if (this.requests.length == 0) {
this.canPerformCommand = false;
} else if (valids.indexOf(this.myresult[0].requestStatus) > 0) {
this.canPerformCommand = true;
}
}
}
I believe you need to change myresult to requests in the canPerformCommand getter:
get canPerformCommand() {
let r = false;
let valids = ['Success', 'Error'];
if (this.requests.length == 0) return false;
if (valids.indexOf(this.requests[0].requestStatus) > 0) {
r = true;
}
return r;
}
Since this getter will be dirty checked by Aurelia, it will be called every 200ms. To avoid that, you can add a computedFrom decorator:
import {computedFrom} from 'aurelia-framework';
export class MyClass {
....
#computedFrom('requests')
get canPerformCommand() { ....
I replaced:
if (valids.indexOf(this.myresult[0].requestStatus) > 0) {
r = true;
}
With
if (valids.includes(this.requests[0].requestStatus)) {
r = true;
}
And now it works. I was using the indexOf function on other pages aswell, and strangely enough it worked on most of them. Must have been something wrong in my model.
Also, I agree that it would be better to use computedFrom.

Alternative to Application.DoEvents in console application to make Forms.WebBrowser load javascripts

I'm using System.Windows.Forms.WebBrowser in console application to render a web page then invoke scripts on it. To render the web page, I use Application.DoEvents to load and execute scripts.
However sometime the app hangs on calling Application.DoEvents. I found no reason. I don't think I'm creating deadlock on the event loop.
Many people on the web says that one should not use Application.DoEvents at all because it creates more problems than it solves. So I'm thinking there must be an alternative to it. But I've searched a lot and find no alternative to Application.DoEvents.
Does anyone know one?
Any information is appreciated. Thank you in advance!
Thanks to Noseratio's help, I finished drafting my code but still there's freezing issue.
Take following code as example(code is too long so I pasted it on pastebin): http://pastebin.com/DkDcrirU
When you run this code, occasionally there will be at least one window fail to close. And if you attach to the frozen process, you will find the code stuck at following line(indicated by ">>>"):
public static bool NavigateLoadAndRender(WebBrowserContext browserContext, string url, TimeSpan loadTimeout, TimeSpan renderTime, out string errMsg)
{
ForceInitActiveXInstance(browserContext);
object axi = null;
Func<Uri> getBrowserUri = null;
Action<Uri> navigateBrowser = null;
Func<IHTMLDocument2> getBrowserDoc = null;
switch (browserContext.WebBrowserType)
{
case WebBrowserTypeEnum.Forms:
{
var browser = browserContext.GetWebBrowserAsFormsType();
getBrowserUri = () => browser.Url;
navigateBrowser = u =>
{
var finished = false;
browserContext.SyncContext.Post(state =>
{
browser.Navigate(u);
finished = true;
}, null);
while (!finished) Thread.Sleep(DefaultConfig_SyncContextPostCheckInterval);
};
getBrowserDoc = () =>
{
IHTMLDocument2 doc = null;
bool finished = false;
browserContext.SyncContext.Post(state =>
{
doc = (IHTMLDocument2)browser.Document.DomDocument;
finished = true;
}, null);
>>> while (!finished) Thread.Sleep(DefaultConfig_SyncContextPostCheckInterval);
return doc;
};
axi = GetActiveXInstance(browserContext);
}
break;
case WebBrowserTypeEnum.Wpf:
{
var browser = browserContext.GetWebBrowserAsWpfType();
axi = GetActiveXInstance(browser);
getBrowserUri = () => browser.Source;
navigateBrowser = u =>
{
var finished = false;
browserContext.SyncContext.Post(state =>
{
browser.Navigate(u);
finished = true;
}, null);
while (!finished) Thread.Sleep(DefaultConfig_SyncContextPostCheckInterval);
};
getBrowserDoc = () =>
{
IHTMLDocument2 doc = null;
bool finished = false;
browserContext.SyncContext.Post(state =>
{
doc = (IHTMLDocument2)browser.Document;
finished = true;
}, null);
while (!finished) Thread.Sleep(DefaultConfig_SyncContextPostCheckInterval);
return doc;
};
axi = GetActiveXInstance(browserContext);
}
break;
default: throw new ArgumentException("unknown browser type", browserContext.WebBrowserType.ToString());
}
var success = NavigateLoadAndRender(
axi, url,
getBrowserUri,
navigateBrowser,
//() => DoEvents(browser),
getBrowserDoc,
loadTimeout, renderTime, out errMsg);
return success;
}
Anyone knows what's happening?