I have a Strapi api and trying to run a unit test
this is the error in the console I am getting
yarn test
yarn run v1.22.5
$ jest --forceExit --detectOpenHandles
● process.exit called with "1"
8 | if (!instance) {
9 | /** the follwing code in copied from `./node_modules/strapi/lib/Strapi.js` */
> 10 | await Strapi().load();
| ^
11 | instance = strapi; // strapi is global now
12 | await instance.app
13 | .use(instance.router.routes()) // populate KOA routes
at Strapi.stop (node_modules/strapi/lib/Strapi.js:263:13)
at node_modules/strapi/lib/Strapi.js:391:16
at async Promise.all (index 5)
at Strapi.runBootstrapFunctions (node_modules/strapi/lib/Strapi.js:394:5)
at Strapi.load (node_modules/strapi/lib/Strapi.js:326:5)
at setupStrapi (tests/helpers/strapi.js:10:5)
at Object.<anonymous> (tests/app.test.js:8:3)
RUNS tests/app.test.js
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
I followed these instructions exactly.
How can I fix this issue?
Thanks
The issue is solved by changing the env folder name into environments
Related
I'm trying to launch a Jest test that just happens to import BabylonJS
I'm getting the error below.
export * from "./abstractScene.js";
^^^^^^
SyntaxError: Unexpected token 'export'
> 1 | import * as BABYLON from "#babylonjs/core";
| ^
2 |
3 | describe("Babylong tests2", () => {
4 | test("Should work please", () => {
When I created a CodeSandbox to test, it works GRRRR
https://codesandbox.io/s/jovial-cherry-svdug7?file=/test/babylon.test.ts
When I git clone and npm i && npm run test it fails with the above error
https://github.com/jtwigg/babylonjs-jest/
I'm having a lot of trouble getting traction with testing in a React app (failed with Mocha a million circular errors)
Any help would be appreciated.
I am trying to test disappearance of dialog box when user clicks "cancel" button on my dialog box using the following test:
it("clicking on cancel hides the confirmation dialog", async() => {
render(<ConfirmationDialog />);
const cancelButton = screen.getByText("Cancel");
fireEvent.click(cancelButton);
await waitForElementToBeRemoved(() => screen.queryByText(/Cancel/i));
expect(screen.queryByText(/Cancel/i)).toBeNull();
});
But the above code throws an error :
TypeError: MutationObserver is not a constructor
24 | const cancelButton = screen.getByText("Cancel");
25 | fireEvent.click(cancelButton);
> 26 | await waitForElementToBeRemoved(() => screen.queryByText(/Cancel/i));
| ^
27 | expect(screen.queryByText(/Cancel/i)).toBeNull();
28 | });
29 | });
Can someone help me understanding this issue as I am new to testing library. Thanks in advance.
You need to mock MutationObserver in your test :
Add #sheerun/mutationobserver-shim package to your project
in setupTests.js (or other Jest configuration file), add the following code :
import MutationObserver from '#sheerun/mutationobserver-shim';
window.MutationObserver = MutationObserver;
Your UI framework certainly depends on it.
There may be other way to mock MutationObserver, this is how I do it but it may not be the best way.
Try this according to: https://github.com/testing-library/dom-testing-library/issues/477
npm install jest-environment-jsdom-sixteen
or
yarn add -D jest-environment-jsdom-sixteen
and then set it via env cli param
"scripts": {
...
"test": "react-scripts test --env=jest-environment-jsdom-sixteen",
...
}
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 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.
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()
};