How can I mock the webkit SpeechRecognition using Jest? - jestjs

I am using webkit SpeechRecognition in my Stencil Project. I have shared function. Can anyone help me with the test cases of below function.
startDictation() {
let recognition = new webkitSpeechRecognition();
recognition.continuous = false;
recognition.interimResults = false;
recognition.lang = "en-US";
recognition.start();
recognition.onresult = (speech) => {
if (speech.results) {
ele.classList.remove("dxp-i-fill");
let result = speech.results[speech.resultIndex];
let transcript = result[0].transcript;
if (result.isFinal) {
if (result[0].confidence < 0.3) {
console.log("Unrecognized result - Please try again");
} else {
this.chatbotnputRef.value = transcript;
}
}
}
};
recognition.onerror = function () {
recognition.stop();
};
}

Related

How do I memoize my backtracking algorithms and make use of dynamic programming?

So I've managed to come up with some solutions to the following problems using backtracking. The problem is that they either get bottom 5% in terms of speed or I just run out of time.
They all follow a very familiar pattern in that they all use a closure backtrack function. This just happens to be my backtracking style and I'm very comfortable with this approach. I'm wondering if there's a way for me to memoize the solutions with just a few lines of code or if I have to completely rethink my brute force approach. I think the thing that I'm struggling with the most here is the shape of the memo data structure for each problem.
Note that I'm familiar with memoizing something as simple as the fibonacci sequence. Thanks! I think if I can get some help on this I'll be able to really take my problem solving to the next level.
https://leetcode.com/problems/word-break-ii/
var wordBreak = function(s, wordDict) {
const results = [];
const backtrack = (prefix, remaining, result) => {
if (!remaining.length) {
results.push(result.slice(0, -1));
}
const appending = remaining.slice(0, 1);
remaining = remaining.slice(1, remaining.length);
if (wordDict.includes(prefix + appending)) {
backtrack('', remaining, result + prefix + appending + ' ');
}
if (remaining) {
backtrack(prefix + appending, remaining, result);
}
}
backtrack('', s, '');
return results;
};
https://leetcode.com/problems/coin-change/
var coinChange = function(coins, amount) {
let min = Infinity;
const backtrack = (result, target) => {
if (target === 0) {
min = Math.min(result.length, min);
}
let i = coins.length - 1;
while (i >= 0) {
if (coins[i] <= target) {
backtrack([...result, coins[i]], target - coins[i]);
}
i--;
}
};
backtrack([], amount);
if (min === Infinity) return -1;
return min;
}
https://leetcode.com/problems/jump-game/
var canJump = function(nums) {
let flag = false;
const target = nums.length - 1;
const backtrack = index => {
if (index === target) {
flag = true;
return;
}
if (nums[index]) {
let n = nums[index];
while (n > 0) {
backtrack(index + n);
n--;
}
}
}
backtrack(0);
return flag;
};
https://leetcode.com/problems/palindrome-partitioning/
var partition = function(s) {
const results = [];
const backtrack = (prefix, str, result) => {
if (!str.length) {
results.push(result);
return;
}
const arr = str.split('');
prefix += arr.shift();
if (prefix.length === 1 || isPalindrome(prefix)) {
backtrack('', arr.join(''), [...result, prefix]);
}
if (arr.length) {
backtrack(prefix, arr.join(''), [...result]);
}
}
const isPalindrome = str =>
str === str.split('').reverse().join('');
backtrack('', s, []);
return results;
};

How to get scenario name from a scenario outline in cypress gherkin setup?

Suppose I have a test case like -
Scenario: Scenario to verify Title Matched
When Navigate to the App "Facebook"
Then verify the "TitleName" Field
How could I get the scenario name from the step definition methods corresponding to " When Navigate to the App Facebook" and "Then verify the "TitleName" Field"
Step definitions methods are -
When('Navigate to the App {string} for demo',(AppURL:string)=>{
if(AppURL=="FaceBook"){
}
});
Then('verify the Title of the page for demo',()=>
{
SampleAPPUI.verfiyTitledemo('');
});
Note: I am using cypres-cucumber with typescript
I'm doing this in a Java-Selenium-Gherkin test suite. It may not be the solution you need, but it will give you some direction about how to get the values:
#BeforeStep
public void doSomethingBeforeStep(Scenario scenario) throws Exception {
testScenario = scenario.getName().toString();
scenarioObj = scenario;
Field f = scenario.getClass().getDeclaredField("testCase");
f.setAccessible(true);
TestCase r = (TestCase) f.get(scenario);
List<PickleStepTestStep> stepDefs = r.getTestSteps()
.stream()
.filter(x -> x instanceof PickleStepTestStep)
.map(x -> (PickleStepTestStep) x)
.collect(Collectors.toList());
PickleStepTestStep currentStepDef = stepDefs.get(currentStepIndex);
testCase = currentStepDef.getStepText();
}
Also, see here and here
This works perfectly for me, though I'm not using TS, the logic behind it should give you a good starting point:
function getScenarioName(){
const _onRunnableRun = Cypress.runner.onRunnableRun
Cypress.runner.onRunnableRun = function (runnableRun, runnable, args) {
const r = runnable
const isHook = r.type === 'hook'
const isAfterAllHook = isHook && r.hookName.match(/after all/)
const isBeforeHook = isHook && r.hookName.match(/before each/)
const test = r.ctx.currentTest || r
var testTitle = test.title //this is the test title
const next = args[0]
if (
isHook &&
r.ctx.currentTest &&
r.ctx.currentTest.trueFn &&
!isAfterAllHook
) {
return next.call(this)
}
const onNext = function (err) {
const fail = function () {
return next.call(this, err)
}
const noFail = function () {
test.err = null
return next.call(this)
}
if (err) {
if (test._retries === -1) {
test._retries = getDefaultRetries()
}
if (isBeforeHook && test._currentRetry < test._retries) {
test.trueFn = test.fn
test.fn = function () {
throw err
}
return noFail()
}
}
return fail()
}
args[0] = onNext
return _onRunnableRun.apply(this, [runnableRun, runnable, args])
}
}

Create mongoose plugin with typescript

I have found on the internet this interesting article about plugins in mongoose. From that site I got this code:
function HidePlugin(schema) {
var toHide = [];
schema.eachPath(function(pathname, schemaType) {
if (schemaType.options && schemaType.options.hide) {
toHide.push(pathname);
}
});
schema.options.toObject = schema.options.toObject || {};
schema.options.toObject.transform = function(doc, ret) {
// Loop over all fields to hide
toHide.forEach(function(pathname) {
// Break the path up by dots to find the actual
// object to delete
var sp = pathname.split('.');
var obj = ret;
for (var i = 0; i < sp.length - 1; ++i) {
if (!obj) {
return;
}
obj = obj[sp[i]];
}
// Delete the actual field
delete obj[sp[sp.length - 1]];
});
return ret;
};
}
The problem is that I use typescript together with node.js. The typescript compiler gives me errors because there are no explicit types. In fact, I do not know exactly what type I have to attribute to the variables in the code

node.js setInterval does not trigger a this. object

When the page loads the console log part of the function works showing me the current seconds + 3, but it does not repeat and the (innerText =....) does not work at all. I only added the console log part to the code to try to troubleshoot, the inner text change is the important part.
class Main {
constructor() {
// Initiate variables
this.TimerTexts = [];
this.infoTexts = [];
this.training = -1; // -1 when no class is being trained
this.videoPlaying = false;
this.currentTime2 = new Date(Date.now());
this.currentTime = new Date(Date.now());
this.remTime = this.currentTime.getSeconds() + 3;
this.looper = window.setInterval(this.intervalfunc(), 1000);
}
// ...
intervalfunc() {
this.TimerTexts.innerText = `Time: ${this.remTime} `;
console.log(this.remTime);
}
// ...
}
The problem is you're calling intervalfunc, not passing in as the function for setInterval.
In addition, you'll need to bind the function to your instance.
this.looper = window.setInterval(this.intervalfunc.bind(this), 1000);
You can use arrow function, inside arrow function you can call intervalfunc.
class Main {
constructor() {
// Initiate variables
this.TimerTexts = [];
this.infoTexts = [];
this.training = -1; // -1 when no class is being trained
this.videoPlaying = false;
this.currentTime2 = new Date(Date.now());
this.currentTime = new Date(Date.now());
this.remTime = this.currentTime.getSeconds() + 3;
this.looper = window.setInterval(()=>this.intervalfunc(), 1000);
}
intervalfunc() {
this.TimerTexts.innerText = `Time: ${this.remTime} `;
console.log(this.remTime);
this.remTime += 3;
}
}
new Main()
OR you can do
class Main {
constructor() {
// Initiate variables
this.TimerTexts = [];
this.infoTexts = [];
this.training = -1; // -1 when no class is being trained
this.videoPlaying = false;
this.currentTime2 = new Date(Date.now());
this.currentTime = new Date(Date.now());
this.remTime = this.currentTime.getSeconds() + 3;
var self = this;
this.looper = window.setInterval(this.intervalfunc.bind(self), 1000);
}
intervalfunc() {
this.TimerTexts.innerText = `Time: ${this.remTime} `;
console.log(this.remTime);
this.remTime += 3;
}
}
new Main()

Using functions as map keys in Haxe

I want to use functions as keys in a Map like this:
var timers : Map<Void->Void, snow.api.Timer>;
But Haxe won't compile:
Abstract Map has no #:to function that accepts IMap<Void -> Void, snow.api.Timer>
Is there a way to do this ?
It's easy to write a custom implementation:
import haxe.Constraints;
class FunctionMap<K:Function,V> implements IMap<K,V> {
private var _keys : Array<K>;
private var _values : Array<V>;
public function new () {
_keys = [];
_values = [];
}
public function get(k:K):Null<V> {
var keyIndex = index(k);
if (keyIndex < 0) {
return null;
} else {
return _values[keyIndex];
}
}
public function set(k:K, v:V):Void {
var keyIndex = index(k);
if (keyIndex < 0) {
_keys.push(k);
_values.push(v);
} else {
_values[keyIndex] = v;
}
}
public function exists(k:K):Bool {
return index(k) >= 0;
}
public function remove(k:K):Bool {
var keyIndex = index(k);
if (keyIndex < 0) {
return false;
} else {
_keys.splice(keyIndex, 1);
_values.splice(keyIndex, 1);
return true;
}
}
public function keys():Iterator<K> {
return _keys.iterator();
}
public function iterator():Iterator<V> {
return _values
.iterator();
}
public function toString():String {
var s = new StringBuf();
s.add("{");
for( i in 0..._keys.length ) {
s.add('<function>');
s.add(" => ");
s.add(Std.string(_values[i]));
if( i < _keys.length - 1 )
s.add(", ");
}
s.add("}");
return s.toString();
}
private function index(key:K) : Int {
for (i in 0..._keys.length) {
if (Reflect.compareMethods(key, _keys[i])) {
return i;
}
}
return -1;
}}
http://try.haxe.org/#DdF31
I just tried this in try.haxe.org, and the compiler doesn't seem to like it, so I'm guessing the answer is "no."
You could get around this with some cleverness:
class Test {
static function main() {
var map:Map<VoidVoid,String>;
map = new Map<VoidVoid,String>();
var thing = {func:foo};
map.set(thing,"bar");
trace(map.get({func:foo})); //fails
trace(map.get(thing)); //succeeds;
}
static function foo():Void
{
}
}
typedef VoidVoid = {
var func:Void->Void;
}
But that's not an ideal solution because wrapping it in a typedef like that will make it fail if it's not the exact same instance, even if the value inside is the same.
I also tried making a Map<Dynamic,String> since you can stuff function references in those, but that didn't work either.
At this point I should ask, what problem are you trying to solve this way? Perhaps it could be better solved some other way.

Resources