Jest export syntax error when running tests
I have the following simple test:
describe("BlogLayout", () => {
it("should render correctly", () => {
const props = {
children: <p>blog layout content</p>,
}
const container = render(<BlogLayout {...props} />)
expect(container.getByText("blog layout content")).toBeInTheDocument()
})
})
but I am getting the following error:
I have tried to add this to my jest config file:
transformIgnorePatterns: ["./utils/themeFontGenerator"],
themeGenerator
(a js file) is where export const letterSpacingMap = {
comes from.
See also questions close to this topic
-
How to display result of map in two different columns
I have a task, but i couldnt get the solution for it in reactjs. I would like to show the result in two columns like:
item 1 | item 4 item 2 | item 5 | item 6
When i loop through the array the columns are getting divided into equal order, but as you see in the diagram i need to split them in 2:3 ratio. I am giving the sandbox link here on what i have tried so far.
// Example class component class Thingy extends React.Component { render() { const secondaryNav = [ { title: "Games", name: ["Roadrash", "Prince of Persia", "Counter Strike"] }, { title: "Resources", name: ["Images", "Videos", "E-books"] }, { title: "Shop", name: ["Shop now"] }, { title: "Account", name: ["Log In", "Register"] }, { title: "Support", name: ["Email", "Call Us", "Get a callback"] } ]; return ( <div className="App"> <div className="container"> <div className="row"> {secondaryNav.map((item, i) => { return ( <div className="col-lg-6 col-md-6"> <h3>{ item.title }</h3> <ul> {item.name.map((items, i) => { return <li>{items}</li> })} </ul> </div>) })} </div> </div> </div> ) } } // Render it ReactDOM.render( <Thingy title="I'm the thingy" />, document.getElementById("react") );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="react"></div> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
-
Axis tick options in d3 charts v4
1.In X-axis not starts from 0, now starts from 1. It should starts from 0.
2.In Y-axis 45 label not showing.
3.In X-axis need to show only like 1,3,5,7,9
Working sample code attached link, kindly check with this.
<https://codepen.io/ganesh88maddy/pen/ZEBqPyL>
Currently using d3 chart version - 4.13.0
-
Problem animation boat floating on ocean, in THREE JS
I have a project to do in THREE JS in WEBGL and I'm blocking. I would like to make a boat that floats on water. Here my boat should follow the waves created by my ocean function as follows:
const gsize = 1000; const res = 1024; const gres = res / 2; const origx = - gsize/2; const origz = - gsize/2; this.ms_Ocean = new Ocean( this._threejs, this._camera, this._scene, { USE_HALF_FLOAT: false, INITIAL_SIZE: 256.0, INITIAL_WIND: [ 10.0, 10.0 ], INITIAL_CHOPPINESS: 1.5, CLEAR_COLOR: [ 1.0, 1.0, 1.0, 0.0 ], GEOMETRY_ORIGIN: [ origx, origz ], SUN_DIRECTION: [ - 1.0, 1.0, 1.0 ], OCEAN_COLOR: new THREE.Vector3( 0.004, 0.016, 0.047 ), SKY_COLOR: new THREE.Vector3( 3.2, 9.6, 12.8 ), EXPOSURE: 0.35, GEOMETRY_RESOLUTION: gres, GEOMETRY_SIZE: gsize, RESOLUTION: res } ); this.ms_Ocean.materialOcean.uniforms[ "u_projectionMatrix" ] = { value: this._camera.projectionMatrix }; this.ms_Ocean.materialOcean.uniforms[ "u_viewMatrix" ] = { value: this._camera.matrixWorldInverse }; this.ms_Ocean.materialOcean.uniforms[ "u_cameraPosition" ] = { value: this._camera.position }; this._scene.add( this.ms_Ocean.oceanMesh );
My question is: How do I follow the movement of the waves? Just like if I had a plan maybe. The boat must have a floating effect on the water.
I have done a lot of research but I can't really find anything that suits me. If anyone has any idea how I can do this. Thank you !
-
How to resolve async timeout in jest test case for async callback?
How to resolve async timeout in jest test case for function?
I worked with node js and jest test. I am facing issue while execute test case for one function "getToken()" that function sometimes getting late to provide response. So jest test case was failed and provide error related to below async timeout.
Error : Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.
Please refer below for "getToken" function and test case for the same.
Actual Function: In refresh_keys.js file
exports.getToken = function(){ return new Promise(function(resolve, reject){ const tokenPayload = { 'client_id': CLIENTID, 'resource': RESOURCE, 'username': config.username, 'password': config.password, 'grant_type': 'password' }; const res = await fetch('https://idad.spadtoken.com/adfs/oauth2/token',{ method: 'POST', headers: { 'Accept': 'application/json' }, body: new URLSearchParams(tokenPayload) }); if(res.status != 200){ reject(res.message); } let tokenData = await res.json(); let access_token = tokenData.access_token; resolve(access_token); }); }
Test Case for Above function:In refresh_keys.test.js file
const refreshKeyTest = require("../refresh_keys"); it("Test case for function getToken", async()=>{ await refreshKeyTest.getToken().then(res => { expect(res).not.tobeNull(); }).catch(err => { }); }, 30000);
How can i resolve this issue related to timeout with test case for above getToken function? Please let me know your thoughts and guidance on how to pass and execute without failed the above test case for getToken function.
-
Adjacent sibling selector with Enzyme dose NOT work
I have html like below:
<input type ="text" id="textInput-FirstName" /> <div class="col error">warning Message</div>
I am trying to get the "warning Message", so I use the code below:
expect(wrapper.find('#textInput-FirstName + div').text()).toBe('warning Message');
But I got an error in the console saying "Method “text” is meant to be run on 1 node. 0 found instead."
I use the $('input#textInput-FirstName + div') in the console in chrome browser and it can find the node. I have no idea why it doesn't work with enzyme. Could anyone tell me is there something wrong? I use “expect(wrapper.find('.error').text()).toBe('warning Message')” and it works fine, but I need to use "input#textInput-FirstName + div" because I have another familiar nodes.
I use "react": "^16.9.0", "jest": "^24.9.0", "enzyme": "^3.11.0"
-
Ts and jest Best way to test routes
I'm starting with jest, and I'm trying to test a route, but I don't know what is the best way to do this, well the way I did it with docker, I go up the docker and start the server express but in my test i create it again and i'm getting my port already in use:
● Hello Word Route › should return a json with value: hello word listen EADDRINUSE: address already in use :::8080 50 | 51 | public start(): void { > 52 | this.server = this.express.listen(Number(process.env.APP_PORT) || 8080, () => {
I have the following bootstrap to start my server:
class ApplicationServer implements Server { private express: Application; private logger: LoggerProvider; private server: http.Server constructor(logger: LoggerProvider) { this.express = express(); this.logger = logger; } public getExpress(): Application { return this.express } public getLogger():LoggerProvider { return this.logger; } public getServer():http.Server { return this.server; } public async close(): Promise<void> { try { this.logger.log(`info`, `closing the http server`, {}) this.server.close() this.logger.log(`info`, `Http server successfully closed`, {}) this.logger.log(`info`, `closing the database`, {}) await closeDB(); this.logger.log(`info`, `Database successfully closed`, {}) } catch (error) { this.logger.log(`error`, error.message, error) } } public async init(): Promise<void> { setupStaticFiles(this.express); setupMiddlewares(this.express); setupRoutest(this.express, this.logger); await connectDB(this.logger) } public start(): void { this.server = this.express.listen(Number(process.env.APP_PORT) || 8080, () => { this.logger.log( `info`, `Server listening on port: ${process.env.APP_PORT || 8080}`, {} ); }); } } export default ApplicationServer;
factory:
export const SetupServer = (): Server => { const logger = new adptLogger({}) return new ApplicationServer(logger) }
start:
(async () => { const server = SetupServer(); try { await server .init() .then(() => server.start()) } catch (error) { console.error(error) server.getLogger().log(`error`, error.message, error) process.exit() } })();
and this is my test::
describe("Hello Word Route", () => { let server= {} as Server; beforeAll(async () => { server = SetupServer(); await server.init(); server.start(); }); afterAll(async () => { }); it("should return a json with value: hello word", async () => { await request(server.getExpress()) .post("api/hello-word") .send({hello: 'hello word'}) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200); }); });
I would like to know what is the best practice to take in this situation to perform route tests my test fail:
Hello Word Route › should return a json with value: hello word listen EADDRINUSE: address already in use :::8080 50 | 51 | public start(): void { > 52 | this.server = this.express.listen(Number(process.env.APP_PORT) || 8080, () => { | ^ 53 | this.logger.log( 54 | `info`, 55 | `Server listening on port: ${process.env.APP_PORT || 8080}`, at Function.listen (node_modules/express/lib/application.js:618:24) at ApplicationServer.start (src/application/infra/app.ts:52:32) at Object.<anonymous> (src/application/routes/hello-word-routes.test.ts:11:12) (node:113) UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:80 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16) (Use `node --trace-warnings ...` to show where the warning was created) (node:113) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:113) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.