Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: pass the return values of beforeAll and beforeEach to the test functions #4903

Closed
ozsay opened this issue Nov 16, 2017 · 12 comments

Comments

@ozsay
Copy link

ozsay commented Nov 16, 2017

I have a situation like this:

describe('describe', () => {
    it('test', () => {
        const initializeData = initialize();
    });

    it('test2', () => {
        const initializeData = initialize();
    });
});

when I have many tests it's tedious to write this line on every test (prefer to avoid storing context object on global/describe scopes).

will be nice to have the ability to pass context objects from before hooks to the test functions as well as the after hooks:

describe('describe', () => {
    beforeAll(() => {
        return mainInitialize();
    });

    beforeEach(() => {
        return initialize();
    });

    afterEach((mainInitData, initData) => {
        clean(initData);
    });
    
    afterAll((mainInitData) => {
       mainClean(mainInitData); 
    });
    
    it('test', (mainInitData, initData) => {
    });

    it('test2', (mainInitData, initData) => {
    });
});
@roeeyud

This comment has been minimized.

@d4nyll
Copy link
Contributor

d4nyll commented Nov 18, 2017

This is similar to the suggestion proposed at #3553.

You can instead do something like this:

let hello;
beforeEach(function () {
  hello = 'hi';
});

afterEach(function () {
  console.log(hello);
});

describe('context', () => {
  it('should work', function () {
    console.log(hello);
  });
});

The describe and it blocks are just functions, so you can just define a variable within the function, and it will be available everywhere within the function scope. Although it's not very clean, I think it's better that to introduce framework-specific (and not very common) conventions as you have suggested here.

@thymikee
Copy link
Collaborator

It's highly unlikely we're going to add extra arguments to the test fn (which is reserved for done callback).

@ozsay
Copy link
Author

ozsay commented Nov 18, 2017

thanks for the reply.

@d4nyll this is kinda what we are doing in some of our tests.. this is what we try to avoid

perhaps a https://nodejs.org/api/async_hooks.html#async_hooks_class_asyncresource solution can be implemented to achieve the same goal (for node >=8).

@cpojer cpojer closed this as completed Nov 18, 2017
@roytz
Copy link

roytz commented Jun 19, 2018

@ozsay @d4nyll also, it means that you can't use that global variable in the tests (assuming their concurrent and the beforeEach set the global variable to a different value each time), no?

@Gwillison415
Copy link

Gwillison415 commented Jul 26, 2018

I wish @d4nyll .. I tried that and within the promises there are values but somehow scope is no extended to the test itself

let styledHtml;
let individualStyledHtml;
let htmlApp;
let individualHtmlApp;

describe('Combined Email Template Functions', () => {
  beforeAll(() => {

    return getHomesliceAppById(1)
    .then(response => {
      htmlApp = hsEmailMessage(response)
      styledHtml = juice.inlineContent(htmlApp, individualCSS)
// works here
      return;
    })
    .then(response => {
      return getIndividualAppById(1)
    })
    .then(response => {
      individualHtmlApp = indvEmailMessage(response)
      individualStyledHtml = juice.inlineContent(individualHtmlApp, individualCSS)
      return;
    })
    .catch(error => console.log(error))
  });

  jest.dontMock('jquery');
// undefined here
  console.log('styledHtml=========', styledHtml);
  document.documentElement.innerHTML = styledHtml;
// undefined here
  console.log("document====", document.documentElement.innerHTML);
  console.log('jquery===', $('.logoAccountBanner').find('td').eq(0).text())
  it('Call to knex getHomesliceAppById returns a string with html', () =>{
    expect.assertions(4);
    expect(styledHtml).toMatch(/html/)
    expect(styledHtml).toMatch(/div/)
    expect(styledHtml).toMatch(/ul/)
    expect(styledHtml).toMatch(/li/)
  })
  // test('It Should read the correct name of the homeSlice App', () => {
  //   expect($('.logoAccountBanner').find('td').eq(0).html()).toEqual(`Hello Team "Vacation Home in Tahoe",`)
  // })
})

@vostrik
Copy link

vostrik commented Feb 13, 2019

@cpojer this issue was closed without any solution or explaining comments.

Can you explain your position, plz?

@SimenB
Copy link
Member

SimenB commented Feb 13, 2019

This was the conclusion:

It's highly unlikely we're going to add extra arguments to the test fn (which is reserved for done callback).

More recent discussion: #7823

@code-matt
Copy link

code-matt commented Apr 28, 2019

For anyone struggling with this here is a workaround, until something comes out of #7823

https://blog.angularindepth.com/how-i-was-completely-wrong-about-setting-up-tearing-down-tests-d3f6501d1718 thanks to this person

This was the only way I found that could work after trying every which thing with just scope. I did not do exactly as they say, instead just using the classRef and storing my variables from beforeEach/All there and then able to access them in the tests.

Put this somewhere for other files to import

export default class ContextHelper {}

import it wherever you need to set some data, then:

beforeAll(async () => {
   const contextClassRef = ContextHelper
   ....
   contextClassRef.editProjectId = 42
})

in some other file where you need an id or something, import it again and:

const contextClassRef = ContextHelper
...
... = `something-${contextClassRef.editProjectId}`

@alirezamirian
Copy link

@d4nyll What you suggest doesn't allow a very useful thing which is extracting the setup logic into a separate function and reuse it in different suits.

@dqisme
Copy link

dqisme commented Oct 13, 2020

It's not about implementable. It's about stateless.

By global variable or namespace property, we definitely could implement the common result from the setting up. But the thing is, we want to keep our tests more independent and as stateless as we can.

@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators May 11, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests