I'm the newbie of flutter test driver. I'm trying to run the test and it's failed with some errors in console logs below. I think I need to extend the default timeout for some specific test steps but not sure how to do that. The documentation doesn't mention well about it.
I have one more question: when my app launches, it takes a long time for render, so I want the test wait for the app complete launching and then executing test. How can I do that?
This is console logs when my app just launches:
This is test failed message:
this is my own waitFor()
static Future<void> waitFor(
FlutterDriver driver, SerializableFinder finder) async {
try {
await driver.waitFor(finder, timeout: timeout);
await FlutterDriverUtils.waitForFlutter(driver, timeout: timeout);
} catch (error) {
throw ('Element does not exists => $error');
}}
Related
The following code errors are not showing on firebase console for some reason:
FirebaseCrashlytics.instance.log('This is brilliant log!');
FirebaseCrashlytics.instance.setCustomKey('str_key', 'hello buffallo');
try {
throw 'error_example';
} catch (e, s) {
FirebaseCrashlytics.instance.recordError(e, s);
}
await FirebaseCrashlytics.instance.recordError(
'No error',
StackTrace.empty,
reason: 'a non-fatal error',
);
However, when I force a crash i.e. use
FirebaseCrashlytics.instance.crash()
This shows up fine! Is there something I am doing wrong?
I am using this version in pub spec: firebase_crashlytics: ^0.4.0+1
I can't use the latest version because of some external dependencies (before you ask)
The errors recorded by recordError are listed as non-fatal exceptions in the Firebase console. At least for iOS they are only uploaded when the app was killed and reopened.
I am trying to convert a simple webpage I have into a PWA in case the site it uses goes down.
I think I have done the majority of the work. The page is installable on my phone and passes all the Chrome lighthouse tests. But I get the following warning,
Web app manifest meets the installability requirements
Warnings: Page does not work offline. The page will not be regarded as installable after Chrome 93, stable release August 2021.
I also get the following warning and error in console,
The FetchEvent for "https://dannyj1984.github.io/index.html" resulted in a network error response: the promise was rejected.
Promise.then (async)
(anonymous) # serviceWorker.js:30
serviceWorker.js:1 Uncaught (in promise) TypeError: Failed to fetch
There is then a warning saying the site cannot be installed as does not work offline. I have read the chrome dev article which says from the chrome release in Aug21 apps that dont work offline wont be installable. But I am stuck on which part of my fetch is causing an issue. The code in my service worker is,
const TGAbxApp = "TG-ABX-App-v1"
const assets = [
//paths to files to add
]
self.addEventListener("install", installEvent => {
installEvent.waitUntil(
caches.open(TGAbxApp).then(cache => {
cache.addAll(assets)
})
)
})
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request);
}
)
);
});
The above code for the fetch part of the service worker I took from Google and as I understand it, it first checks if there is data in the cache stored on install, if not it will request it from the network.
https://developer.chrome.com/blog/improved-pwa-offline-detection/
From Chrome 89 March 2021, it gives a warning if this check does not pass:
The installed service worker fetch event returns an HTTP 200 status code (indicating a successful fetch) in simulated offline mode.
So, in your case, the service worker should return a cached 'index.html' when fetch(event.request) is failed.
I've had the same problem. I re enabled the cache through the developer console->network. fixed
I am trying to setup Flutter Driver tests for my application and the app runs async so I found https://github.com/flutter/flutter/issues/41029 which says all you need to do is add await driver.waitUntilFirstFrameRasterized(); and it should work, while this does stop the test from failing it nos simply does not run.
The app just hangs at the splash screen never even getting into the application itself.
As far as I am understanding, this is all I would need to have setup in order for the test to run
FlutterDriver driver;
// Connect to the Flutter driver before running any tests.
setUpAll(() async {
driver = await FlutterDriver.connect();
await driver.waitUntilFirstFrameRasterized();
// await Directory('screenshots').create();
});
// Close the connection to the driver after the tests have completed.
tearDownAll(() async {
if (driver != null) {
await driver.close();
}
});
However, all I am getting in my terminal is the following output:
VMServiceFlutterDriver: Connecting to Flutter application at http://127.0.0.1:54264/tt9kN4jBSrc=/
VMServiceFlutterDriver: Isolate found with number: 2942164624858163
VMServiceFlutterDriver: Isolate is paused at start.
VMServiceFlutterDriver: Attempting to resume isolate
VMServiceFlutterDriver: Connected to Flutter application.
VMServiceFlutterDriver: waitForCondition message is taking a long time to complete...
I have left it for minutes and nothing happens, I have disabled the firebase initialization in case somehow that is blocking it as I would need to accept the alert dialogue, not that I am even getting that far as I can see.
Turns out I needed to use an IsolatesWorkaround as well
FlutterDriver driver;
IsolatesWorkaround workaround;
// Connect to the Flutter driver before running any tests.
setUpAll(() async {
driver = await FlutterDriver.connect();
workaround = IsolatesWorkaround(driver);
await workaround.resumeIsolates();
await driver.waitUntilFirstFrameRasterized();
if (!await Directory('screenshots').exists()) {
await Directory('screenshots').create();
}
});
// Close the connection to the driver after the tests have completed.
tearDownAll(() async {
await driver?.close();
await workaround.tearDown();
});
See: https://gist.github.com/vishna/03c5d5e8eb14c5e567256782cddce8b4
This question already has an answer here:
Fetch error when building Next.js static website in production
(1 answer)
Closed last year.
I have a very simple NextJS 9.3.5 project.
For now, it has a single pages/users and a single pages/api/users that retrieves all users from a local MongoDB table
It builds fine locally using 'next dev'
But, it fails on 'next build' with ECONNREFUSED error
page/users
import fetch from "node-fetch"
import Link from "next/link"
export async function getStaticProps({ params }) {
const res = await fetch(`http://${process.env.VERCEL_URL}/api/users`)
const users = await res.json()
return { props: { users } }
}
export default function Users({ users }) {
return (
<ul>
{users.map(user => (
<li key={user.id}>
<Link href="/user/[id]" as={`/user/${user._id}`}>
<a>{user.name}</a>
</Link>
</li>
))}
</ul>
);
}
pages/api/users
import mongoMiddleware from "../../lib/api/mongo-middleware";
import apiHandler from "../../lib/api/api-handler";
export default mongoMiddleware(async (req, res, connection, models) => {
const {
method
} = req
apiHandler(res, method, {
GET: (response) => {
models.User.find({}, (error, users) => {
if (error) {
connection.close();
response.status(500).json({ error });
} else {
connection.close();
response.status(200).json(users);
}
})
}
});
})
yarn build
yarn run v1.22.4
$ next build
Browserslist: caniuse-lite is outdated. Please run next command `yarn upgrade`
> Info: Loaded env from .env
Creating an optimized production build
Compiled successfully.
> Info: Loaded env from .env
Automatically optimizing pages ..
Error occurred prerendering page "/users". Read more: https://err.sh/next.js/prerender-error:
FetchError: request to http://localhost:3000/api/users failed, reason: connect ECONNREFUSED 127.0.0.1:3000
Any ideas what is going wrong ? particularly when it works fine with 'next dev' ?
Thank you.
I tried the same few days ago and didn't work... because when we build the app, we don't have localhost available... check this part of the doc - https://nextjs.org/docs/basic-features/data-fetching#write-server-side-code-directly - that said: "You should not fetch an API route from getStaticProps..." -
(Next.js 9.3.6)
Just to be even more explicit on top of what Ricardo Canelas said:
When you do next build, Next goes over all the pages it detects that it can build statically, i.e. all pages that don't define getServerSideProps, but which possibly define getStaticProps and getStaticPaths.
To build those pages, Next calls getStaticPaths to decide which pages you want to build, and then getStaticProps to get the actual data needed to build the page.
Now, if in either of getStaticPaths or getStaticProps you do an API call, e.g. to a JSON backend REST server, then this will get called by next build.
However, if you've integrated both front and backend nicely into a single server, chances are that you have just quit your development server (next dev) and are now trying out a build to see if things still work as sanity check before deployment.
So in that case, the build will try to access your server, and it won't be running, so you get an error like that.
The correct approach is, instead of going through the REST API, you should just do database queries directly from getStaticPaths or getStaticProps. That code never gets run on the client anyways, only server, to it will also be slightly more efficient than doing a useless trip to the API, which then calls the database indirectly. I have a demo that does that here: https://github.com/cirosantilli/node-express-sequelize-nextjs-realworld-example-app/blob/b34c137a9d150466f3e4136b8d1feaa628a71a65/lib/article.ts#L4
export const getStaticPathsArticle: GetStaticPaths = async () => {
return {
fallback: true,
paths: (await sequelize.models.Article.findAll()).map(
article => {
return {
params: {
pid: article.slug,
}
}
}
),
}
}
Note how on that example, both getStaticPaths and getStaticProps (here generalized HoC's for reuse, see also: Module not found: Can't resolve 'fs' in Next.js application ) do direct database queries via sequelize ORM, and don't do any HTTP calls to the external server API.
You should then only do client API calls from the React components on the browser after the initial pages load (i.e. from useEffect et al.), not from getStaticPaths or getStaticProps. BTW, note that as mentioned at: What is the difference between fallback false vs true vs blocking of getStaticPaths with and without revalidate in Next.js SSR/ISR? reducing client calls as much as possible and prerendering on server greatly reduces application complexity.
I'm trying to run jest tests with a Visual Studio Team Services build. These tests run fine and pass locally, but timeout when I run them in VSTS. For each async test that connects to the database, I get
Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.
Here's my setup:
graphql API using Apollo Server
ArangoDB database insider a docker container
A typical test looks like this:
const database = require('../models')
...
describe('database setup', () => {
it('sets up the database and it exists', () => {
console.log(database.db)
const collection=database.db.collection('agents')
console.log(collection)
return database.db.exists().then((result) => {
expect(result).toBeTruthy()
}).catch(err => {console.log(err)})
.then(x => console.log(x))
})
}
...
describe('help functions', () => {
it('gets edge count for a node', async () => {
let result = await database.getEdgeCount('nodes/1', 'inbound')
expect(result).toBeGreaterThan(2)
})
})
I'm running the tests in VSTS with an NPM task. The YAML for this task is basic:
steps:
- task: Npm#1
displayName: npm test
inputs:
command: custom
workingDir: api
verbose: false
customCommand: 'test --runInBand'
I know that the tests are connecting to the database because I can console.log the database object and get the database information.
Other things I've tried:
Promise tests that don't hit the database, such as
it('foo', async () => {
await Promise.resolve()
expect(1).toEqual(1)
})
These pass
Increasing the timeout to 30000. This causes a couple of the tests with database calls to return null.
I was able to fix this, and I think there were two issues going on:
The API was not actually connecting to the database. I was able to fix this by creating a new docker network and attaching both the database and VSTS build agent, as described in this other answer
The tests were starting before the database had completely started up. I added a sleep command in a bash script before the tests which seemed to fix this.