I am trying to start and stop serverless application through code. I am able to start and stop it once all tests pass. However when test fails globalTeardown do not run. You can check sample project here: https://github.com/bilalsha/sls-test-jest/tree/fail_test
teardown.js
module.exports = async function() {
let slsOfflineProcess = global.__SERVERD__;
slsOfflineProcess.stdin.write('q\n');
slsOfflineProcess.stdin.pause();
await slsOfflineProcess.kill('SIGINT');
console.log('Serverless Offline stopped');
};
output
7 | expect(res.statusCode).toEqual(200);
> 8 | expect(res.body).toEqual('Go Serverless v1.0! Your function executed successfully!');
| ^
9 | });
10 | });
11 |
at Object.<anonymous> (handler.test.js:8:20)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 1.972s, estimated 2s
Ran all test suites.
npm ERR! Test failed. See above for more details.
Just eyeballing the docs it looks like your problem is in your jest.config.js when you set it to bail: true
https://github.com/bilalsha/sls-test-jest/blob/fail_test/test/jest.config.js#L3
the docs say that if bail is true it's the same as making the tests stop after the first failure.
https://jestjs.io/docs/en/configuration#bail-number--boolean
I would try changing bail: 0 (the default), and seeing if it produces your expected behavior.
What you can do is add create a script containing the afterAll function:
afterAll(() => {
console.log("I ran");
});
And add the script to the setupFiles or setupFilesAfterEnv. In my case, I ejected one react poc code that had failing tests:
In package.json's Jest config there was this entry:
"jest": {
...
"setupFilesAfterEnv": [
"<rootDir>/src/setupTests.js"
],
...
}
So I added the clause in setupTests.js below is the edited file:
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '#testing-library/jest-dom/extend-expect';
afterAll(() => {
console.log("I ran");
});
Now, when I ran my tests this is the result:
FAIL src/App.test.js
✓ renders learn react link (14ms)
✕ renders class (5ms)
● renders class
expect(jest.fn()).toHaveBeenCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0
18 | // someClass.someProp = "";
19 | render(<App />);
> 20 | expect(track).toHaveBeenCalledTimes(1);
| ^
21 | });
22 |
at Object.<anonymous> (src/App.test.js:20:17)
console.log src/setupTests.js:8
I ran <---------------
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 passed, 2 total
Snapshots: 0 total
Time: 1.352s, estimated 2s
Ran all test suites.
You can see that I ran is there even after failing a test. This is an alternative that you may use, as you have put a bounty I thought maybe solving the problem is more important that why globalTeardown is not working.
Related
Can anyone help here. I couldn't run my test file. Below is the error & test file.
jest.useFakeTimers();
import { orderController } from '../controllers/orderController';
import { orderService } from '../service/orderService';
const res: any = {
send(object: any) {
return object;
}
};
describe("Methods in orderController", () => {
test("checking an API", async () => {
const patientDetailsMock = await jest.spyOn(orderService, 'getPatientDetails');
//const req = {}
//await orderController.createOrder(req, res);
expect(patientDetailsMock).toHaveBeenCalled();
//console.log("hello..inside test",patientDetailsMock)
//expect(patientDetailsMock).toBeTruthy();
});
});
>chandanasriharimummaneni#PTRL671:~/Desktop/demo/JestTesting/node-orders$ npm test
> node-orders#0.0.1 test /home/chandanasriharimummaneni/Desktop/demo/JestTesting/node-orders
> jest
FAIL src/test/orderController.test.ts
Methods in orderController
✕ checking an API (3ms)
● Methods in orderController › checking an API
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
21 | //const req = {}
22 | //await orderController.createOrder(req, res);
> 23 | expect(patientDetailsMock).toHaveBeenCalled();
| ^
24 | //console.log("hello..inside test",patientDetailsMock)
25 | //expect(patientDetailsMock).toBeTruthy();
26 |
at Object.<anonymous> (src/test/orderController.test.ts:23:36)
console.warn node_modules/mongoose/lib/helpers/printJestWarning.js:4
Mongoose: looks like you're trying to test a Mongoose app with Jest's default jsdom test environment. Please make sure you read Mongoose's docs on configuring Jest to test Node.js apps: http://mongoosejs.com/docs/jest.html
console.info node_modules/common-component/lpl/utils/logger/logger.js:184
{ uniqId: '', req: '', jsonObject: '', description: '', arguments: '' } [
'AWS-MIS-Config',
'{"provider":"amazon","keyId":"AKIAT5D3HEZTLAOGKVPG","key":"ZrPLIGmGXWh/nPh0euj+042m+yUUJUzUYvwPMoRR","region":"us-east-1"}'
]
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 1.994s, estimated 2s
Ran all test suites.
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.
What are ways to mock db and methods using mongoose ORM?
Is there any way to mock db connection with object reference ? Also help me to to clear the issue. I have changed jsdom test environment.
Using supertest to test a node.js api for unit and integration testing but the test for integration keep failing; I don't know why I keep receiving an empty object in the reponse.body while I am expecting a result of 30 from the AddNum object. the error comes from the file app.test.js line 19
This is my code for app.test.js
const supertest = require('supertest');
const server = require('../../app');
describe("Calculate", () => {
it('POST /calculate: action: sum', async () => {
const AddNum = {
action: 'sum',
num1: 20,
num2: 10
}
const response = await supertest(server).post("/calculate").send(AddNum)
console.log({response})
expect(response.status).toBe(200)
const expectResult = {result:30}
expect(response.body).toBe(expectResult)
})
})
This is my error from running the test in the command line.
at Object.log (test/integration/app.test.js:15:17)
● Calculate › POST /calculate: action: sum
expect(received).toBe(expected) // Object.is equality
- Expected - 3
+ Received + 1
- Object {
- "result": 30,
- }
+ Object {}
17 |
18 | const expectResult = {result:30}
> 19 | expect(response.body).toBe(expectResult)
| ^
20 | })
21 | })
at Object.toBe (test/integration/app.test.js:19:31)
A worker process has failed to exit gracefully and has been force exited. This is likely caused by tests leaking due to improper teardown. Try running with --detectOpenHandles to find leaks. Active timers can also cause this, ensure that
.unref() was called on them.
Test Suites: 1 failed, 1 passed, 2 total
Tests: 1 failed, 4 skipped, 1 passed, 6 total
Snapshots: 0 total
Time: 2.556 s
Ran all test suites.
While running end-to-end tests of NestJS+Fastify application I noticed the following warnings:
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.
My code follows the docs:
When adding the --detectOpenHandles option I saw the following:
FAIL test/app.e2e-spec.ts
AppController (e2e)
✕ /GET cats (975 ms)
● AppController (e2e) › /GET cats
expect(received).toEqual(expected) // deep equality
Expected: 200
Received: 404
23 | })
24 | .then((result) => {
> 25 | expect(result.statusCode).toEqual(200);
| ^
26 | expect(result.payload).toEqual('API is running.');
27 | });
28 | });
at app.e2e-spec.ts:25:35
So what's the problem?
The pasted example is incomplete, application has to be closed manually just like in the Express example:
afterAll(async () => {
await app.close();
});
And the warning is gone. Also created a PR to improve NestJS' docs.
I'm currently working on an API using node and express.js. For testing and code coverage I use Jest but I have a problem: How I can cover a conditional statement that depends on the node env?
Exemple :
switch (config.env) {
case "development":
// Connect to Dev DB
break;
case "test":
// Connect to Test DB
break;
default:
// Connect to Prod DB
break;
}
With this code when I run test coverage ( cross-env NODE_ENV=test ./node_modules/.bin/jest server/tests --coverage), Jest answers me I cover only the 'test' case, which is normal.
Actually I have added /* istanbul ignore next */ for not having a message telling me that I do not cover all cases.
My question is: There is a way to cover all case or it's ok to disable code coverage for this statement?
You can mock the config object manually.
index.ts:
function connectDatabase(config) {
switch (config.env) {
case 'development':
console.log('Connect to Dev DB');
break;
case 'test':
console.log('Connect to Test DB');
break;
default:
console.log('Connect to Prod DB');
break;
}
}
export { connectDatabase };
Unit test:
import { connectDatabase } from './';
describe('test suites', () => {
const config1 = { env: 'development' };
const config2 = { env: 'test' };
const config3 = { env: 'prod' };
it.each`
config | name
${config1} | ${'Connect to Dev DB'}
${config2} | ${'Connect to Test DB'}
${config3} | ${'Connect to Prod DB'}
`(`$name`, ({ config, name }) => {
const consoleLogSpyOn = jest.spyOn(console, 'log');
connectDatabase(config);
expect(consoleLogSpyOn).toBeCalledWith(name);
});
});
Unit test result with 100% coverage report:
PASS src/stackoverflow/55127764/index.spec.ts
test suites
✓ Connect to Dev DB (10ms)
✓ Connect to Test DB (1ms)
✓ Connect to Prod DB (1ms)
console.log node_modules/jest-mock/build/index.js:860
Connect to Dev DB
console.log node_modules/jest-mock/build/index.js:860
Connect to Test DB
console.log node_modules/jest-mock/build/index.js:860
Connect to Prod DB
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 1.511s, estimated 4s
You can find completed demo here: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/55127764
I am doing jest testing in react native and I have used snackbar in my project. While executing jest i am getting this error.'LENGTH_LONG' is inbuilt variable in snackbar. I am posting where i have used 'LENGTH_LONG' variable and error message. Anyone please help me out
jest "login"
FAIL __tests__\jest\LoginScreen.test.js
● Test suite failed to run
TypeError: Cannot read property 'LENGTH_LONG' of undefined
10 | ScrollView
11 | } from "react-native";
> 12 | import Snackbar from 'react-native-snackbar';
13 |
14 | import { connect } from "react-redux";
15 | import { Button, Text, Divider } from "react-native-elements";
at Object.<anonymous> (node_modules/react-native-snackbar/lib/index.js:1:252)
at Object.<anonymous> (src/screens/login/loginScreen.js:12:26)
at Object.<anonymous> (__tests__/jest/LoginScreen.test.js:3:18)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 2.689s, estimated 4s
Ran all test suites matching /login/i.
Code is
render() {
return (
<View style={styles.mainContainer}>
{this.renderTopLogoContainer()}
{this.renderBottomContainer()}
{this.props.hasError ? Snackbar.show({
title: this.props.error.display_message,
duration: Snackbar.LENGTH_LONG
}) : null}
</View>
);
}
https://github.com/cooperka/react-native-snackbar/tree/master/example
add react-native-snackbar.js file in mocks folder
You have not mentioned whether you are trying to run in ios or android, recently I've seen this issue in ios because I've missed installing the pod.
Try this:
pod install in the ios directory
react-native run-ios
You can also use npm instead of yarn if you prefer.
create a file: 'react-native-snackbar.js' inside the folder 'mocks' with the code
module.exports = {
show: jest.fn()
};