In what order does beforeEach and beforeAll execute? - testing

I'm using Jest-Puppeteer to end2end test a Rails application. Before these tests I want to run some seeds and to work DRY I tell the server to go to a certain URL before each test.
// imports
describe("user can", () => {
// here are some constants
let page;
beforeAll(async () => {
await executeSeed(const1);
await executeSeed(const2);
await executeSeed(const3);
page = await newPrivatePage();
await login(page);
});
beforeEach(async () => {
await page.goto(baseUrl("/some-route"));
});
describe("view some great files", () => {
});
I'd expect the seeds to be executed first, since this is beforeAll and if the first test finishes the beforeEach will be done again, but I can't find it in the documentation of jest (https://jestjs.io/docs/en/api#beforeallfn-timeout)

You can read this article https://jestjs.io/docs/en/setup-teardown.html on Jest document.
beforeAll(() => console.log('1 - beforeAll'));
afterAll(() => console.log('1 - afterAll'));
beforeEach(() => console.log('1 - beforeEach'));
afterEach(() => console.log('1 - afterEach'));
test('', () => console.log('1 - test'));
describe('Scoped / Nested block', () => {
beforeAll(() => console.log('2 - beforeAll'));
afterAll(() => console.log('2 - afterAll'));
beforeEach(() => console.log('2 - beforeEach'));
afterEach(() => console.log('2 - afterEach'));
test('', () => console.log('2 - test'));
});
// 1 - beforeAll
// 1 - beforeEach
// 1 - test
// 1 - afterEach
// 2 - beforeAll
// 1 - beforeEach
// 2 - beforeEach
// 2 - test
// 2 - afterEach
// 1 - afterEach
// 2 - afterAll
// 1 - afterAll
As you can see, beforeAll will be run before all of your test be executed. beforeEach will be run before each of you test. So beforeAll will be run before beforeEach

Related

TypeError: (0 , _stripeReactNative.initStripe) is not a function #1141

I am trying to write a test case. but I am trying to mock stripe npm but not getting success.
Write two basic tests and execute them you can see the error in the console
App.js file
useEffect(() => {
getStripeToken();
initializeStripe();
}, []);
const initializeStripe = () => {
initStripe({
publishableKey:'pk_te9ms7qP6N70007AHphRr',
merchantIdentifier: 'merchant.identifier',
urlScheme: 'your-url-scheme'
});
};
App.test.tsx
test('Stripe Payment render correctly', () => {
render(<StripePayment />);
});
test('Stripe Payment snapshot capture correctly', () => {
const componentTree = render(<StripePayment />).toJSON();
expect(componentTree).toMatchSnapshot();
});
jest.setup.js
import mock from '#stripe/stripe-react-native/jest/mock.js';
jest.mock('#stripe/stripe-react-native', () => mock);
Received following error

Why these mocks are not resetting?

I am making app with Nextjs and Jest and React Testing Library for testing. I use nock for mock axios responses.
My tests:
axios.defaults.adapter = require('axios/lib/adapters/http');
describe('Contacts component', () => {
beforeEach(() => {
nock.disableNetConnect();
nock(BACKEND_URL).defaultReplyHeaders(nockReplyHeaders).options('/api/user').reply(200);
nock(BACKEND_URL).defaultReplyHeaders(nockReplyHeaders).get('/api/user').reply(200, RootUserJson);
});
afterEach(() => {
// mock resetting
nock.restore();
});
it('loads first contacts list', async () => {
// these mocks works fine
nock(BACKEND_URL)
.defaultReplyHeaders(nockReplyHeaders)
.options(`/api/friendship/friends/${RootUserJson.id}?page=1`)
.reply(200);
nock(BACKEND_URL)
.defaultReplyHeaders(nockReplyHeaders)
.get(`/api/friendship/friends/${RootUserJson.id}?page=1`)
.reply(200, ContactsFirstPageJson);
render(
<Contacts />
);
// some expects..
});
it('loads empty list and show empty component', async () => {
// these mocks not returns EmptyJson, it return json from first test
nock(BACKEND_URL)
.defaultReplyHeaders(nockReplyHeaders)
.options(`/api/friendship/friends/${RootUserJson.id}?page=1`)
.reply(200);
nock(BACKEND_URL)
.defaultReplyHeaders(nockReplyHeaders)
.get(`/api/friendship/friends/${RootUserJson.id}?page=1`)
.reply(200, EmptyJson);
render(
<Contacts />
);
const emptyComponent = await screen.findByText('No contacts, add some friends');
expect(emptyComponent).toBeInTheDocument();
});
});
Mocks resetting not working. Mock from second tests returns json from first test. I want to reset mock after each it(). Please for help.

Jest: putting variable directly in describe-block vs. beforeAll

I know that having shared state between tests is bad practice and should be avoided if possible. But I'm just curious how are these two constructs below different in Jest:
describe-block
describe('test suite', () => {
const theAnswer = 42;
test('a test case', () => {
expect(theAnswer + 1).toEqual(43);
});
test('another test case', () => {
expect(theAnswer + -1).toEqual(41);
});
});
vs.
beforeAll
describe('test suite with beforeAll', () => {
let theAnswer;
beforeAll(() => {
theAnswer = 42;
});
test('a test case', () => {
expect(theAnswer + 1).toEqual(43);
});
test('another test case', () => {
expect(theAnswer + -1).toEqual(41);
});
});
What's the significance of using beforeAll if we can directly declare a shared variable/state in the describe block?
From the doc One-Time Setup:
This can be especially bothersome when the setup is asynchronous, so you can't do it inline. Jest provides beforeAll and afterAll to handle this situation.
If the setup is synchronous like yours, declaring the variables in the describe block is OK.
If setup was synchronous, you could do this without beforeAll. The key is that Jest will wait for a promise to resolve, so you can have asynchronous setup as well.
But if the setup is asynchronous, you can't do it inside describe block. You must do it in before* and after* hooks.
E.g.
describe('test suite', () => {
let theAnswer;
beforeAll((done) => {
setTimeout(() => {
theAnswer = 42;
done();
}, 1_000);
});
test('a test case', () => {
expect(theAnswer + 1).toEqual(43);
});
test('another test case', () => {
expect(theAnswer + -1).toEqual(41);
});
});
Jest will wait for the setup to be done before running the test cases.
See the doc about beforeAll

how to mock window.eventBus.$on - Vue.js | Jest Framework

Need to test the emitted value for test case coverage.
window.eventBus.$on('filter-search-content', () => {
console.log('Yes it was emitted');
this.showFilter = true;
});
This what i have tried. But it's not worked out for me.
it('should all the elements rendered', () => {
global.eventBus = {
$on: jest.fn(),
}
// global.eventBus.$emit('filter-search-content'); --> This also not working
wrapper = mountAppointment(data);
wrapper.vm.eventBus.$emit('filter-search-content');
expect(wrapper.vm.showFilter).toBe(true);
});
Here is the example code we can follow.
emitEvent() {
this.$emit("myEvent", "name", "password")
}
Here is the test case
describe("Emitter", () => {
it("emits an event with two arguments", () => {
const wrapper = shallowMount(Emitter)
wrapper.vm.emitEvent()
console.log(wrapper.emitted())
})
})

Vue testing beforeRouteEnter navigationGuard with JEST / Vue-test-utils

i have a component which uses
beforeRouteEnter(to, from, next) {
return next((vm) => {
vm.cacheName = from.name
})
},
it takes previous route name and saves it into current component variable calld - cacheName
how can i test that with JEST? i was trying to
test('test', async () => {
await wrapper.vm.$options.beforeRouteEnter(null, null, () => {
return (wrapper.vm.cacheName = 'testname')
})
console.log(wrapper.vm.cacheName)
})
but it doesnt rly cover the test.. i guess i have to mock next function somehow but i just dont know how, please help me :<
Testing beforeRouteEnter:
I was trying with jest, In my use case, it worked with the below code.
vue-testing-handbook Reference Link
it('should test beforeRouteEnter', async () => {
const wrapper = shallowMount(Component, {
stubs,
localVue,
store,
router,
i18n,
});
const next = jest.fn();
Component.beforeRouteEnter.call(wrapper.vm, undefined, undefined, next);
await wrapper.vm.$nextTick();
expect(next).toHaveBeenCalledWith('/');
});