Pact JS - The pact mock service wasn't running when verify was called - pact

When I run my Pact tests I get the following error - "The pact mock service wasn't running when verify was called".
The project I am running tests in is in GitHub - https://github.com/pactflow/example-consumer/tree/master/src
I run the tests using this command - npm t
See error in my detail below -
The pact mock service wasn't running when verify was called
12 | describe('API Pact test', () => {
13 | beforeAll(() => mockProvider.setup());
> 14 | afterEach(() => mockProvider.verify());
| ^
15 | afterAll(() => mockProvider.finalize());
16 |
17 | describe('retrieving a product', () => {
at Pact.verify (node_modules/#pact-foundation/src/httpPact.ts:136:9)
at Object.<anonymous> (src/api.pact.spec.js:14:32)

The problem was that the path to my project was too long. I read that Pact only allows 80 characters for path lengths.

I was getting the same error: The pact mock service wasn't running when verify was called but looking at the debug logs seemed that it was throwing
thrown: "Exceeded timeout of 5000 ms for a hook.
Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."
to fix it, I added the code below, as suggested by izhaoqing here.
// jest.config.js
module.exports = {
// ...
testTimeout: 20000
}
Seems to be related to version 27 of jest as another project with 26 is working fine.

Related

Fly.io deployment - secret env variables undefined

I'm pretty new to coding (started in August) and will try to provide all the necessary info needed!
I am working on a blog for a friend in Next.js that has a ghost backend for her to work in (deployment on fly.io worked perfectly fine with a ready-made docker image) and an extra frontend page. We need the latter because she wants the blog posts to appear in a specific way. So we cannot use the provided templates by ghost.
The frontend website is the one, I could not deploy yet. It fails during the build phase and shows the following error:
#10 46.29 Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error
#10 46.29 TypeError: Failed to parse URL from undefined/ghost/api/v3/content/posts/?key=undefined&fields=title,slug,html&include=tags
#10 46.29 at Object.fetch (node:internal/deps/undici/undici:11118:11)
#10 46.29 at async getPosts (/app/.next/server/pages/index.js:33:17)
#10 46.29 at async getStaticProps (/app/.next/server/pages/index.js:38:19)
#10 46.29 at async renderToHTML (/app/node_modules/next/dist/server/render.js:385:20)
#10 46.29 at async /app/node_modules/next/dist/export/worker.js:277:36
#10 46.29 at async Span.traceAsyncFn (/app/node_modules/next/dist/trace/trace.js:79:20)
#10 46.29 info - Generating static pages (1/6)
#10 46.29 (node:114) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time
#10 46.29 (Use `node --trace-warnings ...` to show where the warning was created)
#10 46.36 info - Generating static pages (2/6)
#10 46.38 info - Generating static pages (4/6)
#10 46.42 info - Generating static pages (6/6)
#10 46.42
#10 46.43 > Build error occurred
So, the variables somehow don’t "reach" my fetch request: undefined/ghost/api/v3/content/posts/?key=undefined&fields=title,slug,html&include=tags. The associated function looks like this:
async function getPosts() {
const res = await fetch(
`${process.env.BLOG_URL}/ghost/api/v3/content/posts/?key=${process.env.CONTENT_API_KEY}&fields=title,slug,html&include=tags`,
).then((resp) => resp.json());
const posts = res.posts;
return posts;
}
My Dockerfile looks like this:
# Initialize builder layer
FROM node:18-alpine AS builder
ENV NODE_ENV production
# Install necessary tools
RUN apk add --no-cache libc6-compat yq --repository=https://dl-cdn.alpinelinux.org/alpine/edge/community
WORKDIR /app
# Copy the content of the project to the machine
COPY . .
RUN yq --inplace --output-format=json '.dependencies = .dependencies * (.devDependencies | to_entries | map(select(.key | test("^(typescript|#types/*|#upleveled/)"))) | from_entries)' package.json
RUN --mount=type=secret,id=BLOG_URL \
BLOG_URL="$(cat /run/secrets/BLOG_URL)"
RUN --mount=type=secret,id=CONTENT_API_KEY \
CONTENT_API_KEY="$(cat /run/secrets/CONTENT_API_KEY)"
RUN yarn install --frozen-lockfile
RUN yarn build
# Initialize runner layer
FROM node:18-alpine AS runner
ENV NODE_ENV production
# Copy built app
COPY --from=builder /app/.next ./.next
# Copy only necessary files to run the app (minimize production app size, improve performance)
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/public ./public
COPY --from=builder /app/package.json ./
COPY --from=builder /app/.env.production ./
CMD ["yarn", "start"]
The build problem seems to have something to do with the environment variables, which I have tried to 1) set via flyctl secrets set BLOG_URL=xyz for runtime and 2) tried to set via flyctl deploy --build-secret BLOG_URL=xyz and tell docker to use it in my Dockerfile like so (also see above):
RUN --mount=type=secret,id=BLOG_URL \
BLOG_URL="$(cat /run/secrets/BLOG_URL)"
RUN --mount=type=secret,id=CONTENT_API_KEY \
CONTENT_API_KEY="$(cat /run/secrets/CONTENT_API_KEY)"
The (runtime) secrets exist when I run flyctl secrets list.
I don’t know what is going on and why neither the build secrets nor the runtime secrets change anything about my ‘undefined’ URL.
I appreciate any hints and help!
I could find a solution/a workaround with the help of a friend. The issue could be solved in a part of the code, that I did not post yet:
export const getServerSideProps = async () => {
const posts = await getPosts();
if (typeof posts === 'undefined') {
return {
props: {
error: 'Nothing to see here',
},
};
}
return {
props: { posts },
};
};
In this piece of code, I had used getStaticProps which needs the variables during build. By using getServerSideProps, the runtime env variables are enough.
So, now I do not use any docker secrets, neither during deployment nor in my Dockerfile, only runtime fly secrets.
🆒

Local image import in nextjs with jest (react-testing-library) failed

I'm getting the below error while writing the test case against my home page, which contains the landing image.
FAIL src/test/unit/pages/home.test.tsx
● Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
/Users/xys/Documents/work/working/project-code/client/src/asset/images/landing/landing.png:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){�PNG
SyntaxError: Invalid or unexpected token
> 1 | import LandingImage from '~/asset/images/landing/landing.png';
| ^
2 |
3 | const Images = {
4 | LandingImage
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)
at Object.<anonymous> (src/asset/index.tsx:1:1)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.012 s
Ran all test suites related to changed files.
I have tried the below-suggested solution in jest.config.js file but unable to resolve this.
"\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/client/src/tests/unit/fileMock.js",
Also, I tried all the solutions suggested in the below site.
Importing images breaks jest test
If you try to import an image (binary file), please try this within your package.json file:
"jest": {
"moduleNameMapper": {
"\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/client/src/tests/unit/fileMock.js",
}
}
get more information in jest docs here: https://jestjs.io/docs/code-transformation

Github Probot create-probot-app: 'Cannot POST /' (404) response to webhook request

Testing out the npx create-probot-app; tried with each of the starters and the same problem exists.
I create, build, and run the app, and then configure and install the app on github, I am able to receive webhook events but I'm seeing my local app respond with a 404.
smee receives the event
error: Error: cannot POST / (404)
ERROR (server): Not Found
Error: Not Found
at Request.callback (/Users/X/Projects/Y/compiler/githubapp/x-bot/node_modules/superagent/lib/node/index.js:884:15)
at IncomingMessage.<anonymous> (/Users/X/Projects/Y/compiler/githubapp/x-bot/node_modules/superagent/lib/node/index.js:1127:20)
at IncomingMessage.emit (events.js:326:22)
at IncomingMessage.EventEmitter.emit (domain.js:483:12)
at endReadableNT (_stream_readable.js:1241:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
status: 404
My index.ts:
export = (app: Probot) => {
app.on("issues.opened", async (context) => {
const issueComment = context.issue({
body: "Thanks for opening this issue!",
});
await context.octokit.issues.createComment(issueComment);
});
// For more information on building apps:
// https://probot.github.io/docs/
// To get your app running against GitHub, see:
// https://probot.github.io/docs/development/
};
I've checked that my environment variables appear to be setup correctly in .env
In sum, github is sending a webhook, smee is receiving it, but my local app is responding with 404: cannot post /
Not able to get the example app to process webhook events due to what appears to be a routing issue. Anyone encountered this before?
Make sure you don't have any other applications running on Port 3000. Create React App uses 3000 by default and can cause the error you are describing.
One of the possible reasons could be that your GitHub App does not have privileges to take that action. Would it be possible that your GitHub App is missing the 'issues' privilege setting? (https://docs.github.com/en/rest/reference/permissions-required-for-github-apps#permission-on-issues)

TestCafe integration with cucumber - test cases in github project time out

I have been experimenting with javascript frameworks for test automation and one of them is testCafe. I have been able to set up a simple TestCafe project and run some test cases for my application. However, now, the requirement is to have some kinda BDD support built in it. I looked up a few testCafe-cucumber integration projects on GitHub but I can't get them to run. here are a few that I tried:-
1) https://github.com/rquellh/testcafe-cucumber
- I cloned the repo,
- did npm install,
- run the test cases using "npm test",
- blank browser launches but test doesn't run. I see this error in VS code console:
× Before # features\support\hooks.js:46
Error: function timed out, ensure the promise resolves within 20000 milliseconds
at Timeout._onTimeout (C:\Users\Mo\Desktop\TestCafe\github\testCafeBDD\testcafe-cucumber\node_modules\cucumber\src\user_code_runner.js:61:18)
at ontimeout (timers.js:482:11)
at tryOnTimeout (timers.js:317:5)
at Timer.listOnTimeout (timers.js:277:5)
× After # features\support\hooks.js:60
ReferenceError: testController is not defined
Then I tried another gitHub project namely this one : https://github.com/kiwigrid/gherkin-testcafe
the run command in readme doesn't work for me, it doesn't even recognize the "gherkin-testcafe".
When I run my TestCafe test cases without the cucumber I have this line in my package.json
"scripts": {
"test": "testcafe chrome Tests/ -e --proxy https.proxy.mycompany.com:8000"
},
the proxy is mentioned because I am behind a proxy and without this the browser launches but does not run any test cases. I found this fix on testCafe site
I am guessing(not sure yet) this could be the issue with cucumber integration as well. None of these frameworks work as they don't set up the proxy anywhere. Can someone point me in the right direction? if the proxy needs to be set up then where in the framework does it need to go- an example would be helpful?
TestCafe/Cucumber integrations rely on starting TestCafe runner programmatically.
In the repo, search for this sequence:
const runner = tc.createRunner();
return runner
.src('./test.js')
.screenshots('reports/screenshots/', true)
.browsers(browser)
.run()
.catch(function(error) {
console.error(error);
});
or search for this sequence:
await runner
.browsers(browsers)
.specs(specs)
.steps(steps)
.concurrency(concurrency)
.startApp(app, appInitDelay)
.tags(tags)
.run(...)
Chain the useProxy method on runner object (do it before the run()method):
const runner = tc.createRunner();
return runner
.src('./test.js')
.screenshots('reports/screenshots/', true)
.browsers(browser)
.useProxy('username:password#proxy.mycorp.com')
.run()
.catch(function(error) {
console.error(error);
});

WildFly deploying

When deploy application server WildFly 8.1.0, the following error occurs .
Thu Oct 01 13:31:07 GMT+300 2015
Failed to enable rest-api-0.1-SNAPSHOT.war.
Unexpected HTTP response: 500
Request
{
"address" => [("deployment" => "rest-api-0.1-SNAPSHOT.war")],
"operation" => "deploy"
}
Response
Internal Server Error
{
"outcome" => "failed",
"failure-description" => {"JBAS014671: Failed services" => {"jboss.deployment.unit.\"rest-api-0.1-SNAPSHOT.war\".POST_MODULE" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"rest-api-0.1-SNAPSHOT.war\".POST_MODULE: JBAS018733: Failed to process phase POST_MODULE of deployment \"rest-api-0.1-SNAPSHOT.war\"
Caused by: java.lang.RuntimeException: JBAS018757: Error getting reflective information for class org.eclipse.jetty.server.handler.IdleTimeoutHandler$1 with ClassLoader ModuleClassLoader for Module \"deployment.rest-api-0.1-SNAPSHOT.war:main\" from Service Module Loader
Caused by: java.lang.IncompatibleClassChangeError: Implementing class"}},
"rolled-back" => true
}
And only on one machine to the other all right and runs deploying and enable it. What could be the reason of it?
server.log
Looks like the program you are deploying throws an IncompatibleClassChangeError. Causes for that error are discussed here. You should try to follow these steps:
Undeploy the old build
Clean the build
Stop Wildfly
Delete all temporary sources
Start WildFly
Build the application
Deploy the build
Error getting reflective information for class org.eclipse.jetty.server.handler.IdleTimeoutHandler$1 with ClassLoader ModuleClassLoader for Module \"deployment.rest-api-0.1-SNAPSHOT.war
This means, somehow, there is some Jetty class. IT really smells when in a deployment made for WildFly or any JEE compliant server in general, there is a class from package org.eclipse.jetty*.
Please try removing that dependency. I hope you're using JAX-RS for your REST API.
I think you miss here the right Jboss-deplyoment-structure.xml

Resources