After doing myfunc = jest.spyOn(...) for a library method, is there a way to capture the returned value so I can perform expect() tests on the returned object? It seems I can only do expect(myfunc).toHaveLastReturnedWith(...) but this does not let me acquire what it actually last returned with.
I want to check the length of the arrays, as the contents are dynamic.
Try this:
expect(myfunc.mock.results[0].value).toBe(...)
So if your mock looked like this:
const myfunc = jest.fn().mockReturnValue(['foo', 'bar']
myfunc()
Then myfunc.mock.results[0].value would return ['foo', 'bar'] and you could check for the value and also possible the length or anything else that you wanna assert.
Jest Docs: mock-property
Related
I have an 2 dimentional array:
def test = [[88,3,2],[22,33,4],[88,3,3]]
test.sort
what i need now is to create each item into string and prefix it with string "test-"
so the end result would ne one dimentional array:
def endResult = ["test-88.3.2"],["test-88.3.3"],["test-22.33.4"]
if i do:
test.each {println it.join(".")}
it prints the first part but as written i need to save it and add prefix
im new to groovy any help would be great
The each method does not produce any result - it only iterates the input collection and allows you to do something with each element (e.g. print it to the console like in the example you showed in your question.)
If you want to manipulate each element of the collection and store it as a new collection, you can use the collect method which also takes a closure as a parameter. This closure is applied to each element of the input collection, and the return value of this closure is used to return a new collection from the collect method.
Something like this should do the trick for you:
def test = [[88,3,2],[22,33,4],[88,3,3]]
def endResult = test.collect { 'test-' + it.join('.') }
println endResult // [test-88.3.2, test-22.33.4, test-88.3.3]
It's worth mentioning that the closure we passed to the collect method uses so-called implicit return - there is no return keyword, but the value it produces from 'test-' + it.join('.') is returned implicitly.
def define():
a = input("Language:")
b = input("Version:")
return a,b
def print_language():
f = define()
print(f[0],f[1])
define()
print_language()
Language:Python
Version:3.8
Language:Python
Version:3.8
Python 3.8
The output of this is that it calls the function twice like this. I know the solution to this, only to call the 2nd function, but my question is:
Is it possible to assign the values we get from the first function with "return" to a variable, without calling the first function itself, and then, for example, when we send a value into the first function, can we call it and use it without repeating it a second time?
You need to pass the results of define() to print_language(), e.g.:
def print_language(f):
print(f[0],f[1])
result = define()
print_language(result)
Or this can be collapsed to:
print_language(define())
This is a weird one print return 9 and then it prints 1 , also i checked debugger in pycharm and the (stuff) keeps counting down for some reason
def repeater(stuff):
if stuff != 9:
stuff += 1
print(stuff)
repeater(stuff)
return stuff
print(repeater(0))
When you call repeater(stuff), you're not passing the variable stuff, you're passing a copy of the variable stuff. When you say stuff += 1, you're not modifying the stuff you called the function with, you're modifying a copy of it. That change isn't reflected in the original when you exit the function.
Then, when the function exits, you don't do anything with the returned value of stuff - which is, again, copied out of the function in reverse. Python does let you call the function without using its return value, but it looks like your intent here is to apply the returned value of repeater(stuff) to stuff.
To accomplish that, simply change the line
repeater(stuff)
to
stuff = repeater(stuff)
The reason for that additional 1 that is coming in the end is that repeater(stuff) is returning the value of stuff which is being received by your print statement i.e. print(repeater(0)). When all the recursive calls return back, none of the values are stored/used but the very first call that was made by print(repeater(0)) obtains a value of 1 because repeater(stuff) returns the value of stuff which would be 1 after stuff += 1 during the first call.
You can read more about how recursion works for more clarity.
I'm trying to generate HashMap object that will have properties and values set from parsed text input. Working fine with simple assigned, but wanted to make it more clever and use inject.
def result = new HashMap();
def buildLog = """
BuildDir:
MSBuildProjectFile:test.csproj
TargetName: test
Compile:
Reference:
""".trim().readLines()*.trim()
buildLog.each {
def (k,v) = it.tokenize(':')
result."${k.trim()}"=v?.trim()
}
println "\nResult:\n${result.collect { k,v -> "\t$k='$v'\n" }.join()}"
generates expected output:
Result:
Reference='null'
MSBuildProjectFile='test.csproj'
BuildDir='null'
TargetName='test'
Compile='null'
after replacing the insides of .each { } closure with injection:
it.tokenize(':').inject({ key, value -> result."${key}" = value?.trim()})
the results generated are missing unset values
Result:
MSBuildProjectFile='test.csproj'
TargetName='test'
Am I doing something wrong, tried with inject ("", {...}) but it seems to push may keys into values.
inject is basically a reduce. The reducing function takes two arguments, the result of the previous iteration or the initial value (e.g. the accumulator) and the next value from the sequence. So it could be made to work, but since you only expect one sequence value, it just convolutes the code.
I do see a great use for collectEntries here, as it allows you to create a Map using either small key/values map, or lists of two elements. And the latter you have:
result = buildLog.collectEntries {
it.split(":",2)*.trim()
}
should work for your code instead of buildLog.each
I'm having trouble checking whether two strings are equal when one of them was passed through a splat argument. Because coffeescript uses strict comparisons, and because it makes a copy of the arguments when they go through a splat, I can't get the strings to compare properly without resorting to backticks. Is there a better way? Here's a minimal piece of code that demonstrates the problem:
check=(arg) ->
if arg == 'foo' then "'#{arg}'=='foo'" else "'#{arg}'!='foo'"
emit=(args...) ->
check(args)
console.log(emit('foo'))
console.log(check('foo'))
The output from this will be as follows:
> coffee mincase.coffee
'foo'!='foo'
'foo'=='foo'
EDIT:
mu is too short gave me the key, so the revised working code looks like this (everything is the same except emit)
emit=(args...)->
check.apply(null,args)
When you use a splat, the splat puts the splatted arguments into an array. For example:
f = (x...) -> console.log(x instanceof Array)
f(6)
will give you a true in the console. The fine manual isn't so fine in this case, it doesn't exactly spell it out, it assumes that you understand how JavaScript's arguments object works and leaves out the explicit splat puts your arguments into an array part.
So you end up passing an array to check and an array compared with a string using CoffeeScript's == (or JavaScript's ===) will never be true.
If you want emit to check the first argument, then you need to say so:
emit = (args...) -> check(args[0])
Demo: http://jsfiddle.net/ambiguous/TBndM/