0

Using mocha trying to export variable from testHook file but getting undefined in test file, my code is ::

Test File :

 var xyz = require("testHook").xyz;

 class test1 {
 execute() {
  describe("test suite 1", async () => {
    it("test 1", async () => {
      console.log(xyz);
    });
    });
  }
}
new test1().execute();

testHook.js

 function abc()
 {
 //do some stuff and assume value to be returned is 10 
 exports.xyz = 10;;
 }
 beforeEach(() => {
  abc();
  console.log(this.xyz);
 });

Output ::

 test suite 1
 10
 undefined
 ✓ test 1: 1ms
 Suite duration: 0.009 s, Tests: 1
 1 passing (10ms)

1 Answer 1

1

you should import TestHook;

var testHook = require("testHook");

class test1 {
 execute() {
   describe("test suite 1", async () => {
     it("test 1", async () => {
       console.log(testHook.xyz);
     });
   });
 }
}
new test1().execute();

By the time xyz is imported, the test has not begun yet, therefore the beforeEach is not called yet. So, the imported xyz is the copy of the original variable before being set.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.