Jest - mock `config` module - unit-testing

I'm writing a unit test where I want to mock the value returned when calling config.
In the module I call config several times, and want to mock the returned value from one of the calls:
import config from 'config';
const REGION: string = config.get('AWS_DYNAMODB_REGION');
const ENDPOINTS: (string | undefined)[] = config.get('AWS_DYNAMODB_ENDPOINTS');
const CLIENT_TIMEOUT: number = config.get('AWS_DYNAMODB_CLIENT_TIMEOUT');
How can I mock the returned value for config.get('AWS_DYNAMODB_CLIENT_TIMEOUT') for example.
Please advise.

Resolved in the following way:
jest.mock('config');
import config from 'config';
let configGetSpy: jest.SpyInstance;
configGetSpy = jest.spyOn(config, 'get');
configGetSpy
.mockReturnValueOnce('AWS_DYNAMODB_REGION')
.mockReturnValueOnce([])
.mockReturnValueOnce(1001)
.mockReturnValueOnce(false)
.mockReturnValueOnce(false);

Related

How to skip mocked image and get real image attributes with Jest?

I am writing unit tests and I want to test an img atrributes. However, when I make an assertion, I get mocked img attributes which is under __mocks__>fileMock.js. Because I mock files, I only get mocked file atrributes. How can I skip mocked files in my tests?
describe('Buttons', () => {
test('Clear filters work after filtering tools, workflows and using searchbar', async () => {
render(<HeaderBar {...defaults} />);
const clearFilterButton = screen.getByRole('button', { name: 'Clear Filters' });
const toolsButton = screen.getByRole('button', { name: 'TOOLS' });
const selectedTools = await within(toolsButton).findByRole('img');
expect(selectedTools).toHaveAttribute('src', 'images/tools-selected.png');
});
And test result is :
Buttons › Clear filters work after filtering tools, workflows and using searchbar
expect(element).toHaveAttribute("src", "images/tools-selected.png") // element.getAttribute("src") === "images/tools-selected.png"
Expected the element to have attribute:
src="images/tools-selected.png"
Received:
src="test-file-stub"
39 | const toolsButton = screen.getByRole('button', { name: 'TOOLS' });
40 | const selectedTools = await within(toolsButton).findByRole('img');
> 41 | expect(selectedTools).toHaveAttribute('src', 'images/tools-selected.png');
I need to test real image, and skip mocking that img in my test.
It sounds like you have a manual user module mock defined in a __mock__ folder next to your actual code.
In that case the mock is used in any test file where you call jest.mock('moduleName') unless automock is set to true in which case the mock will always be used.
If you are explicitly mocking the file using jest.mock('moduleName') then simply remove that from the test file where you want to use the actual code instead of the mock.
If you have automock set to true in your Jest config then you can tell Jest to use the original code file in a given test by using jest.unmock('moduleName').

Is there a way to use global jest mocks with Quasar?

I want to mock my i18n object globally.
I'm following a guideline. I'm creating jest.init.ts file inside my jest folder. It contains following rules:
import { config } from "#vue/test-utils"
config.mocks["$t"] = () => ""
But my tests fail with the error:
TypeError: _vm.$t is not a function
I've also tried to import quasar implementation of vue-test utils ('#quasar/quasar-app-extension-testing-unit-jest'), but the result is the same
I found this https://testing.quasar.dev/packages/unit-jest/. Here is a section for mocking i18n.

PagedResultList Instance in Grails 3.1.7 Unit Test

Is it possible to create PagedResultList instance or Mock?
For Background: Currently I´m writing Controller Unit tests. If it is necessary I stubbing Service function calls. But some of this functions have PagedResultList as return type. So i have to inject a PagedResultList instance or null.
In some cases I need an instance because the controller do something like this:
testFunction(){
def result = sampleService.doSomething()
if (result.empty) {
variable = "it´s empty"
}
render variable
}
My Test looking like this:
void "sample Test"(){
given:
controller.sampleService = Mock(SampleService)
PagedResultList emptyPagedResultList = ?????
when:
controller.testFunction()
then:
1 * controller.sampleService.doSomething() >> emptyPagedResultList
response.text == "it´s empty"
}
Someone can help me to replace the ????? with a pice of code to fix this issue?
Thanks in advance.
Yes, there are a couple options here:
You could use a real PagedResultList as the emptyPagedResultList - See FooControllerSpec.groovy line 11 for an example
You could use another Spock Mock() as the emptyPagedResultList - See FooControllerSpec.groovy line 25 for an example

Play WS standalone for 2.5.x

I want to create a Play web service client outside a Play application. For Play WS version 2.4.x it is easy to find that it is done like this:
val config = new NingAsyncHttpClientConfigBuilder().build()
val builder = new AsyncHttpClientConfig.Builder(config)
val client = new NingWSClient(builder.build)
However in 2.5.x the NingWSClient is now deprecated - instead the AhcWSClient should be used.
Unfortunately, I didn't find a complete example that explains the creation and usage of a AhcWsClient outside of Play. Currently I go with this:
import play.api.libs.ws.ahc.AhcWSClient
import akka.stream.ActorMaterializer
import akka.actor.ActorSystem
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
val ws = AhcWSClient()
val req = ws.url("http://example.com").get().map{
resp => resp.body
}(system.dispatcher)
Is this the correct way of creating a AhcWsClient? And is there a way of creating a AhcWSClient without an ActorSystem?
You are probably using compile time dependency injection, otherwise you would just use #Inject() (ws: WSClient), right?.
There is one example in the docs: https://www.playframework.com/documentation/2.5.x/ScalaWS#using-wsclient
So you could write something like this in your application loader:
lazy val ws = {
import com.typesafe.config.ConfigFactory
import play.api._
import play.api.libs.ws._
import play.api.libs.ws.ahc.{AhcWSClient, AhcWSClientConfig}
import play.api.libs.ws.ahc.AhcConfigBuilder
import org.asynchttpclient.AsyncHttpClientConfig
val configuration = Configuration.reference ++ Configuration(ConfigFactory.parseString(
"""
|ws.followRedirects = true
""".stripMargin))
val parser = new WSConfigParser(configuration, environment)
val config = new AhcWSClientConfig(wsClientConfig = parser.parse())
val builder = new AhcConfigBuilder(config)
val logging = new AsyncHttpClientConfig.AdditionalChannelInitializer() {
override def initChannel(channel: io.netty.channel.Channel): Unit = {
channel.pipeline.addFirst("log", new io.netty.handler.logging.LoggingHandler("debug"))
}
}
val ahcBuilder = builder.configure()
ahcBuilder.setHttpAdditionalChannelInitializer(logging)
val ahcConfig = ahcBuilder.build()
new AhcWSClient(ahcConfig)
}
applicationLifecycle.addStopHook(() => Future.successful(ws.close))
And then inject ws to your controllers. I'm not 100% sure with this approach, I would be happy if some Play guru could validate this.
Regarding an ActorSystem, you need it only to get a thread pool for resolving that Future. You can also just import or inject the default execution context:
play.api.libs.concurrent.Execution.Implicits.defaultContext.
Or you can use your own:
implicit val wsContext: ExecutionContext = actorSystem.dispatchers.lookup("contexts.your-special-ws-config").
AFAIK this is the proper way to create the AhcWSClient - at least in 2.5.0 and 2.5.1 - as seen in the Scala API
You can, of course, always take another HTTP client - there are many available for Scala - like Newman, Spray client, etc. (although Spray is also based on Akka so you would have to create an actor system as well)

grails unit test - java.lang.NullPointerException: Cannot invoke method finish() on null object

I am not being able to run unit test in grails. I have a TransactionController(available at github as well) with method transactionAnalytics which I want to test as below,
TransactionController.groovy
package eccount
import org.codehaus.groovy.grails.web.json.JSONObject
import org.springframework.dao.DataIntegrityViolationException
import grails.converters.JSON
class TransactionController {
def transactionService
def transactionAnalytics = {
searchRequest = searchRequest ?: new SearchRequest(requestParams: new HashMap<String, String>())
configureRequestParams()
def responseBytes = transactionService.getSearchResponse(searchRequest)
def jsonResponse
if (responseBytes)
jsonResponse = JSON.parse(responseBytes)
else
jsonResponse = new JSONObject()
render jsonResponse as JSON
}
}
Corresponding Tests for TransactionController#transactionAnalytics (also available at github)is as below,
TransactionControllerTests.groovy
package eccount
import org.junit.*
import grails.test.mixin.*
#TestFor(TransactionController)
class TransactionControllerTests {
def INDEX_NAME = "gccount"
void testTransactionAnalytics(){
Map<String, String> params = new HashMap<String, String>()
params.put("indexName",INDEX_NAME)
//println params.get("indexName")
//controller.params = params
controller.params.indexName = "gccount"
controller.transactionAnalytics()
def jsonResponse = controller.response.json
println jsonResponse
}
}
When I run the method of the Controller, I get following exception
prayag#prayag:/backup/gccount$ grails test-app TransactionController.transactionAnalytics
| Environment set to test.....
| Running 1 unit test...
| Failure: Test mechanism
| java.lang.NullPointerException: Cannot invoke method finish() on null object
at org.junit.runner.notification.RunNotifier$2.notifyListener(RunNotifier.java:71)
at org.junit.runner.notification.RunNotifier$SafeNotifier.run(RunNotifier.java:41)
at org.junit.runner.notification.RunNotifier.fireTestRunFinished(RunNotifier.java:68)
at _GrailsTest_groovy$_run_closure4.doCall(_GrailsTest_groovy:290)
at _GrailsTest_groovy$_run_closure2.doCall(_GrailsTest_groovy:248)
at _GrailsTest_groovy$_run_closure1_closure21.doCall(_GrailsTest_groovy:195)
at _GrailsTest_groovy$_run_closure1.doCall(_GrailsTest_groovy:184)
at TestApp$_run_closure1.doCall(TestApp.groovy:82)
| Completed 0 unit test, 1 failed in 2723ms
| Packaging Grails application.....
[scalaPlugin] Compiling Scala sources from plugins to /home/prayag/.grails/2.1.1/projects/cashless/plugin-classes
[scalaPlugin] Compiling Scala sources to /backup/gccount/target/classes
| Compiling 2 source files
Configuring Spring Security Core ...
... finished configuring Spring Security Core
sandbox user created
role created
stall created with a user
| Tests FAILED - view reports in /backup/gccount/target/test-reports
Again, there's no reports left at file:///backup/gccount/target/test-reports.
Anyways, who is actually null here?
Resources
9 Testing - Reference Documentation
http://mrhaki.blogspot.com/2010/04/grails-goodness-invoking-single-test.html
https://stackoverflow.com/a/3736549/432903
try:
grails test-app TransactionController.testTransactionAnalytics
you forgot the "test" in front of the method name...
and yes... it seems, you don't have to write it in the classname, but in the methodname you have to...
Grails Goodness: Invoking a Single Test Method seems posting wrong information because following code wouldn't work.
$ grails test-app TransactionController.transactionAnalytics
The correct one would be with initialized transactionService
$ grails test-app TransactionControllerTests.testTransactionAnalytics
OR
$ grails test-app TransactionController.testTransactionAnalytics