I'm trying to mock twilio module but it's being a pain. I'm new to Jest and I've read docs but it's not clear how should I mock a class and a type.
This is the code that I'm trying to mock:
const Twilio = require('twilio')
const client = new Twilio('sid', 'auth')
const response = new Twilio.twiml.VoiceResponse()
The part of constructor new Twilio is doing fine:
jest.mock('twilio', () => class {
constructor (accountSid, authToken) {
this.conferences = {
list () {
return mockTwilioListConferences()
}
}
}
})
But how can I mock the part new Twilio.twiml.VoiceResponse()?
Twilio developer evangelist here.
Disclaimer, I haven't tried this, but here's how I believe this works.
The twiml property on the Twilio class is just that, a property. In your mock you instantly return a new anonymous class, but if you add the property to the class itself before you return you should find it is then part of your mock.
For example:
jest.mock('twilio', () => {
const mockClass = class {
constructor (accountSid, authToken) {
this.conferences = {
list () {
return mockTwilioListConferences()
}
}
}
}
mockClass.twiml = {
// complete your mock implementation here
}
return mockClass;
);
Let me know if that helps at all.
Related
I am using JDBI 3 and have written the following utility function.
public class JdbiHelper {
// ...
public <T, DAO> T fetch(final Function<DAO, T> function, Class<DAO> daoClass) {
return dbi.withHandle(handle -> {
final DAO dao = handle.attach(daoClass);
try {
return function.apply(dao);
}
finally {
handle.close();
}
});
}
}
which I can call in methods like this
public Optional<Account> findByEmailAddress(final String emailAddress) {
if (!exists(emailAddress))
return Optional.empty();
return jdbiHelper.fetch(dao -> ofNullable(dao.selectByEmailAddress(emailAddress)), AccountDAO.class);
}
private boolean exists(final String emailAddress) {
return jdbiHelper.fetch(dao -> dao.count(emailAddress) > 0, AccountDAO.class);
}
I am trying to write a test for the findByEmailAddress mocking jdbiHelper using Mockito 2 but cannot work out how to mock the dao -> part of the method.
I've tried using jdbiHelper.fetch(any(Function.class), eq(AccountDAO.class)) but as there are two different expectations of what to return it fails trying to cast one or the other.
Passing in a mocked Function causes a NPE as the dao param is null.
I have this Java test with Mockito:
public class PersistentNodeDeserializerTests {
#Test
public void userInfoPersistentNodeDeserializer() {
PersistentNode node = mock(PersistentNode.class);
when(node.stringChild("username")).thenReturn("cliff12");
//more stuff
}
}
PersistentNode is a Kotlin class:
open class PersistentNode(private val path: PersistentNodePath, val content: Any) {
val stringPath: String
get() = path.get()
val key: String
get() {
val parts = stringPath.split("/");
return parts[parts.size - 1];
}
val mapContent: Map<String, Any>
get() {
return content as HashMap<String, Any>
}
fun stringChild(child: String): String {
return mapContent.get(child) as String
}
}
I get this error:
kotlin.TypeCastException: null cannot be cast to non-null type
java.util.HashMap
How can I mock the property stringChild properly?
this library may solve your issue https://github.com/nhaarman/mockito-kotlin
EDIT: sorry, didn't realize you were using a Java test. If it's an option, try writing your test in kotlin too
I'm trying to write a unit test for a method which has takes in a .class parameter.
For example:
ExampleService {
def myExample(clazz){
//do stuff and return some object
}
}
/* How the above function gets used */
AnotherExampleService extends exampleService {
def blah() {
def obj = myExample(AnotherClass.class)
}
}
/* Now I need to test the above blah() function */
AnotherExampleServiceSpec extends Specification {
def "test blah"() {
//The following doesn't seem to work
ExampleService.metaClass.myExample = { def arg1 -> obj }
}
}
I'm pretty new to Groovy/Grails, so any help would be much appreciated. I basically want to know why my unit test doesn't seem to work, and how to test such a function that takes in a paramter of a class instance.
Thank you for your help!
I would probably subclass the ExampleService in the test. So it looked like:
ExampleService {
def myExample(clazz){
//do stuff and return some object
}
}
AnotherExampleService extends ExampleService {
def exampleService
def blah() {
def obj = myExample(AnotherClass)
}
}
AnotherExampleServiceSpec extends Specification {
def "test blah"() {
given:
AnotherExampleService service = new AnotherExampleService() {
#Override
def myExample(clazz){
//whatever you want to do
return whatEverResult
}
when:
def result = service.blah (SomeClass)
then:
result
}
}
As you can see the myExample methods is overridden here to return some mock value and there's no tinkering with metaclass :-) To make it easier for Groovy you can explicitly state the input type e.g. def myExample(Class clazz).
I am using Microsoft Fakes framework within VS2012.
I use the following code to shim instance methods of my type.
using (ShimsContext.Create())
{
ShimDateTime.NowGet = () => { return new DateTime(1949, 10, 1); };
DateTime now = DateTime.Now; // shim works for the static property DateTime.Now.
Class1 dependency = new Class1();
using (ShimsContext.Create())
{
ShimClass1 shim1 = new ShimClass1();
StubClass1 stub1 = new StubClass1();
shim1.method1 = () => { return "shim method1"; };
shim1.IMethod1 = () => { return "shim IMethod1"; };
String s1 = dependency.method1();// shim doesn't work for the instance method.
String s2 = dependency.IMethod1();// shim doesn't work for the instance method.
}
The class1 and looks like this:
public class Class1 : Interface1
{
public String method1()
{
return "real method1";
}
//Interface 1 member
public string IMethod1()
{
return "real IMethod1";
}
}
I expect the s1 and s2 to be the shimed output, but it is still real output.
Why?
If 'method1' was static your shim would have worked. However with the current code you have not really shimmed out 'method1'. You need to either associate the instance with the shim instance
Class1 dependency = new ShimClass1() { Method1 = () => { return "Shim.Method1"; } };
or associate all instance methods with your delegate
ShimClass1.AllInstances.Method1 = (q)=> { return "Shim.Method1"; };
Also I dont see the need to have the ShimsContext.Create() done twice
If you want to use stubs to redirect IMethod1 you should be consuming the StubInterface1 instead
Class1 dependency = new StubInterface1() { Method1 = () { return ""; } };
Variations of these are available on msdn for reference
I have a static method with ref parameters in my legacy (untestable) dll. I am trying to write unit tests for a class that calls into this method.
public static class Branding
{
...
...
static public bool GetBranding(Int32 providerId,
Int32 employerId,
string brandingElement,
ref string brandingValue)
...
...
}
I need help writing a shim statement for this call
ShimBranding.GetBrandingInt32Int32StringStringRef =
( providerId, employerId, element, { ====> WHAT GOES HERE <===== } )
=>
true;
Thanks!
using (ShimsContext.Create())
{
ShimBranding.GetBrandingInt32Int32StringStringRef =
(int providerId, int employerId, string brandingElement, ref string brandingValue) =>
{
brandingValue = "Blah";
return true;
};
}