Detox with Split.IO - react-native

I found a jest mock for split.io for react-native. I am now trying to use this mock so that I do not receive network timeouts because split.io is trying to sync in the background. Here is the mock:
jest.mock('#splitsoftware/splitio-react-native', () => {
const splitio = jest.requireActual('#splitsoftware/splitio-react-native');
return {
...splitio,
SplitFactory: () => {
return splitio.SplitFactory({
core: {
authorizationKey: 'localhost',
},
// Mock your splits and treatments here
features: {},
sync: {
localhostMode: splitio.LocalhostFromObject(),
},
});
},
};
});
I currently put this in my detox init.js file, but it doesn't seem to be doing anything. The only way, so far, I have been able to get my tests to run is to just immediately destroy my SplitFactory as soon as I create it (not through the mock). Obviously, this isn't ideal since I'd have to change the code every time I wanted to run it. I tried creating a .mock.ts file, but that also didn't get read, and when I tried to adjust my metro.config.js, it just failed to run at all. Does anyone have any ideas of how I can get this to run properly in detox for iOS, or have experience with this?

I had the same issue with split.io and detox, when a particular split.io would block my tests indefinitely. The only work around i found was
await device.disableSynchronization();
found here

Related

Close redis connection when using NestJS Queues

I'm trying to setup E2E tests in a NestJS project, however, jest output looks like this:
Jest did not exit one second after the test run has completed
After a lot of reading this is because there are some resources, not yet liberated, after some debugging it turns there's an open connection to redis created by ioredis which is used by bull which is used by NestJS to do task queue processing. The thing is that I don't have a reference to the connection in the test code, so how can I close it? I'm tearing down the Nest application in the afterAll jest's hook like this:
afterAll(async () => {
await app.close();
});
but it does nothing, the connection is still there and the jest error message persists. I know I can just add the --forceExit to the jest command but that is not solving anything, it's just hiding the problem under the rug.
This took me awhile to figure out. You need to close the module in the afterAll hook. I was able to find this from looking at the tests in the nestJS Bull repo.
describe('RedisTest', () => {
let module: TestingModule;
beforeAll(async () => {
module = Test.createTestingModule({
imports: [
BullModule.registerQueueAsync({
name: 'test2',
}),
],
});
});
afterAll(async () => {
await module.close();
});
});
https://github.com/nestjs/bull/blob/master/e2e/module.e2e-spec.ts
After struggling almost to getting depressed i found a solution that worked for me.
I'm using "#nestjs/bull": "^0.3.1", "bull": "^3.21.1".
because the queue from bull package uses redis, it keeps the connection open although the module & app are closed.
await moduleRef.close();
await app.close();
i realized that when using --detectOpenHandles while relying on leaked-handles library for more information, you will see something like this in the console:
tcp stream {
fd: 20,
readable: true,
writable: false,
address: {},
serverAddr: null
}
tcp handle leaked at one of:
at /media/user/somePartitionName/Workspace/Nest/project-
name/node_modules/ioredis/built/connectors/StandaloneConnector.js:58:45
tcp stream {
fd: 22,
readable: true,
writable: true,
address: { address: '127.0.0.1', family: 'IPv4', port: 34876 },
serverAddr: null
}
Solution
using beforEach() & afterEach()
in beforEach(), add this instruction to get an instance of your queue :
queue = moduleRef.get(getQueueToken("queuename"));
in afterEach(), close the queue like so: (also close your app & module for better practice)
await queue.close();
Note
using beforAll() & afterAll() doesn't work and the same problem occurs, at least from what i have tried, both beforEach() & afterEach() work combined.
You don't have to add queue.close() to every test, just close queues in their own service/provider using OnModuleDestroy Hook:
#Injectable()
export class ServicesConsumer implements OnModuleDestroy {
constructor(
#InjectQueue('services')
private readonly servicesQueue: Queue,
) { }
async onModuleDestroy() {
await this.servicesQueue.close();
}

I'm trying to use react-call-detection to detect a missed call number but something is not working

Hey there to everyone!
I'm posting my first question so I'll try to be as clear as possible!
I'm building a native android app using react-native(0.61.5), I'm using setState hook instead of the classic state and I want to use the react-native-call-detection library(1.8.2).
What is the problem?
function startListenerTapped() {
console.log('start');
callDetector = new CallDetectorManager((event, number) => {
console.log(event);
console.log('inside call detector');
if (event === 'Missed') {
console.log(event);
console.log(number);
setMissedCaller(number);
}
},
true,
() => { console.error('access denied') },
{
title: 'Phone State Permission',
message: 'This app needs access to your phone state in order to react and/or to adapt to incoming calls.'
}
)
}
I run this function when my component mounts, callDetector is set as undefined, I get the 'start' log but when I simulate a call on my AVD nothing happens.
From what I understood the CallDetectorManager works like an event listener, right?
Or do I need to start it every time a call happens?
Another thing I've had a problem with was when I was trying to run a build for the app. I have Gradle 6.0 and I had an error with the react-native-call-detection:
Attribute application#allowBackup value=(false) from AndroidManifest.xml:13:7-34
is also present at [:react-native-call-detection] AndroidManifest.xml:21:9-35 value=(true).
Suggestion: add 'tools:replace="android:allowBackup"' to <application> element at
AndroidManifest.xml:7:5-117 to override.
I couldn't really understand what this meant, and the only thing that I've found that solved it was to create a react-native.config.js file with this line of code in it:
module.exports = { dependencies: { 'react-native-call-detection': { platforms: { android: null, }, }, }, };
Another thing that I've only noticed now is that I have a problem with the module of the library.
Could not find a declaration file for module 'react-native-call-detection'.
'c:/folders/projectName/node_modules/react-native-call-detection/index.js' implicitly has an 'any' type.
Try `npm install #types/react-native-call-detection` if it exists or add a new declaration (.d.ts) file containing `declare module 'react-native-call-detection';`
Does anybody knows what that means?!
I think I start to think that it means that I need to find an alternative to this library... AHAHA!
Any kind of help or solution would be more than welcome!
Thanks in advance for everything!

Multiple connections with same name are created in e2e test of NestJs with in memory database

I have NestJs application with TypeORM configured with mysql. I want to have e2e(integration) test and for that reason I want to have in memory database in the tests which I configured this way:
{
type: 'sqlite',
database: ':memory:',
synchronize: true,
dropSchema: true,
entities: [`dist/**/*.entity{.ts,.js}`],
}
And the setup of the tests
beforeEach(async () => {
const moduleFixture: TestingModule =
await Test.createTestingModule({imports: [AppModule, UserModule]})
.overrideProvider(TypeOrmConfigService).useClass(MockTypeOrmConfigService)
.compile();
app = await moduleFixture.createNestApplication();
await app.init();
});
. When running the test I got
AlreadyHasActiveConnectionError: Cannot create a new connection named "default", because connection with such name already exist and it now has an active connection session.
at new AlreadyHasActiveConnectionError (/Users/user/workspace/app/src/error/AlreadyHasActiveConnectionError.ts:8:9)
at ConnectionManager.Object.<anonymous>.ConnectionManager.create (/Users/user/workspace/app/src/connection/ConnectionManager.ts:57:23)
at Object.<anonymous> (/Users/user/workspace/app/src/index.ts:228:35)
at step (/Users/user/workspace/app/node_modules/tslib/tslib.js:136:27)
at Object.next (/Users/user/workspace/app/node_modules/tslib/tslib.js:117:57)
at /Users/user/workspace/app/node_modules/tslib/tslib.js:110:75
at new Promise (<anonymous>)
at Object.__awaiter (/Users/user/workspace/app/node_modules/tslib/tslib.js:106:16)
at Object.createConnection (/Users/user/workspace/app/node_modules/typeorm/index.js:186:20)
at rxjs_1.defer (/Users/user/workspace/app/node_modules/#nestjs/typeorm/dist/typeorm-core.module.js:151:29)
(node:19140) UnhandledPromiseRejectionWarning: AlreadyHasActiveConnectionError: Caught error after test environment was torn down
If I move the setup from beforeEach in beforeAll block it's ok, but I'm afraid that when I create several specs the error will come back. How should be handled properly?
EDIT:
The problem was that each test is making a setup of the application and so creates a new connection.The solution was to use "keepConnectionAlive: true," in order all tests to reuse same connection.
keepCOnnectionAlive: true is the way to go
Using keepConnectionAlive: true produced the following error for me.
Jest did not exit one second after the test run has completed.
This usually means that there are asynchronous operations that weren't
stopped in your tests. Consider running Jest with
--detectOpenHandles to troubleshoot this issue.
Adding the below to each e2e test fixed my issue:
afterEach(async () => {
await app.close();
});
Base on 0xCAP's answer, you can do something like this also.
// jest.setup.ts
jest.mock("/path/to/database/config/object", () => {
const { databaseConfig, ...rest } = jest.requireActual("/path/to/database/config/object")
return {
...rest,
databaseConfig: {
...databaseConfig,
keepConnectionAlive: true // replace old config
}
}
})
// jest.config.js
module.exports = {
...other options
setupFilesAfterEnv: ["jest.setup.ts"],
}

mocha programmatically set vue error handler

I find myself writing this at the start of pretty much all of my unit tests in mocha:
it('should do something', (done) => {
Vue.config.errorHandler = done;
// do something aynchronous
});
By default, Vue catches all errors itself and logs them to the console, so mocha can't see them. This code makes sure that thrown errors fail the tests.
Is there a way with mocha to do this without having to start every single async test with this line of code? If I have to write / use a plugin, that's fine.
Try:
Vue.config.errorHandler = function (err, vm, info) {
throw err
}
in your test entry.

How to perfectly isolate and clear environments between each test?

I'm trying to connect to SoundCloud using CasperJS. What is interesting is once you signed in and rerun the login feature later, the previous login is still active. Before going any further, here is the code:
casper.thenOpen('https://soundcloud.com/', function() {
casper.click('.header__login');
popup = /soundcloud\.com\/connect/;
casper.waitForPopup(popup, function() {
casper.withPopup(popup, function() {
selectors = {
'#username': username,
'#password': password
};
casper.fillSelectors('form.log-in', selectors, false);
casper.click('#authorize');
});
});
});
If you run this code at least twice, you should see the following error appears:
CasperError: Cannot dispatch mousedown event on nonexistent selector: .header__login
If you analyse the logs you will see that the second time, you were redirected to https://soundcloud.com/stream meaning that you were already logged in.
I did some research to clear environments between each test but it seems that the following lines don't solve the problem.
phantom.clearCookies()
casper.clear()
localStorage.clear()
sessionStorage.clear()
Technically, I'm really interested about understanding what is happening here. Maybe SoundCloud built a system to also store some variables server-side. In this case, I would have to log out before login. But my question is how can I perfectly isolate and clear everything between each test? Does someone know how to make the environment unsigned between each test?
To clear server-side session cache, calling: phantom.clearCookies(); did the trick for me. This cleared my session between test files.
Example here:
casper.test.begin("Test", {
test: function(test) {
casper.start(
"http://example.com",
function() {
... //Some testing here
}
);
casper.run(function() {
test.done();
});
},
tearDown: function(test) {
phantom.clearCookies();
}
});
If you're still having issues, check the way you are executing your tests.
Where did you call casper.clear() ?
I think you have to call it immediately after you have opened a page like:
casper.start('http://www.google.fr/', function() {
this.clear(); // javascript execution in this page has been stopped
//rest of code
});
From the doc: Clears the current page execution environment context. Useful to avoid having previously loaded DOM contents being still active.