Cypress import spec file - testing

I would like to import spec files to the one main test
import heroBannerTest from './hero-banner.spec'
import fabTest from './fab.spec'
import dealerLocatorTest from './dealer-locator.spec'
let urls = getUrls()
urls.forEach((url) => {
describe(url, () => {
it(`Visit Page`, () => {
cy.visit(url, { timeout: 30000 })
})
it(`Hero Banner`, () => {
heroBannerTest()
})
it(`FAB button`, () => {
fabTest()
})
it(`Dealer Locator Link`, () => {
dealerLocatorTest()
})
})
})
but spec file need to look like
export default function() {
cy.get('.main-nav-list', { timeout: 3000 })
cy.get('.main-nav-list [class^=icon-map-pin] a', { timeout: 10000 })
.click()
cy.get('#cms20 .results-sidebar.map-locations > ul li')
.should('exist')
})
}
and I can't run this test separately any1 can help ?

Hi I have found solution for this
import dealerLocatorTest from './dealer-locator.spec'
import getUrls from '../fixtures/get-urls'
export default function() {
cy.get('.main-nav-list', { timeout: 3000 })
cy.get('.main-nav-list [class^=icon-map-pin] a', { timeout: 10000 })
.click()
cy.get('#cms20 .results-sidebar.map-locations > ul li')
.should('exist')
}
let urls = getUrls()
urls.forEach((url) => {
describe(url, () => {
it(`Dealer Locator Test`, () => {
cy.visit(url, { timeout: 30000 })
dealerLocatorTest()
})
})
})
it allows me to import test from here and run test separately

Suggestion: from cypress convetional testing, i would suggest you put test which you want to reuse/concept of modularization into CYPRESS COMMANDS (THE FILE IS cypress/support/commands.js). That way, you will store a test as a custom command and just call it using "cy.commandName()" where ever you want in your project.

Related

ThrottlerStorageRedisService on integration service

im trying to build an integration test for a module in NestJS and im having a problem with this package.
I created a redis intances with docker on my local but nothing seems to work.
what am i doing wrong ?
import { config } from '#clients-service/common/config';
import {
DEFAULT_THROTTLE_TTL_SECONDS,
DEFAULT_THROTTLE_LIMIT,
} from '#clients-service/common/constants';
import { RedisCacheModule } from '#clients-service/common/providers/redis-cache';
import { INestApplication } from '#nestjs/common';
import { Test, TestingModule } from '#nestjs/testing';
import { ThrottlerModule } from '#nestjs/throttler';
import { ThrottlerStorageRedisService } from 'nestjs-throttler-storage-redis';
const MAX_TIME = 5 * 1000;
describe('[Module] Clients Service', () => {
jest.setTimeout(MAX_TIME);
let app: INestApplication;
beforeAll(async () => {
const test = new ThrottlerStorageRedisService({
host: config.redis.host,
port: config.redis.port,
password: config.redis.password,
});
const module: TestingModule = await Test.createTestingModule({
imports: [
RedisCacheModule,
ThrottlerModule.forRoot({
ttl: DEFAULT_THROTTLE_TTL_SECONDS,
limit: DEFAULT_THROTTLE_LIMIT,
storage: test,
}),
],
}).compile();
app = module.createNestApplication();
await app.init();
});
it('should be defined', () => {
expect(app).toBeDefined();
});
});

React Native: 'Jest did not exit one second after the test run has completed' with #testing-library/react-hooks and react-query

I am using jest and #testing-library/react-hooks to test hooks implemented with react-query in my React Native code.
The tests work ok, but at the end, I am getting:
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.
Here is my simplified code:
import { renderHook } from '#testing-library/react-hooks'
import React from 'react'
import { QueryClient, QueryClientProvider, useQuery } from 'react-query'
const useSomething = () => {
return useQuery('myquery', () => 'OK')
}
beforeAll((done) => {
done()
})
afterAll((done) => {
done()
})
// test cases
describe('Testing something', () => {
it('should do something', async () => {
const queryClient = new QueryClient()
const wrapper = ({ children }: { children: React.ReactFragment }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
const { result, waitFor } = renderHook(() => useSomething(), { wrapper })
await waitFor(() => {
return result.current.isSuccess
})
expect(result.current.data).toBe('OK')
})
})
I tried using cleanup, done, unmount, etc. before each/all with no results. If I remove useQuery from useSomething, the problem disappears.
Any idea how to fix it?
This issue has been reported in the past here:
https://github.com/tannerlinsley/react-query/issues/1847
The issue is caused by the react-query garbage collection timer running, which defaults to 5 minutes. Solutions are, as described in the issue:
clearing the queryCache after each test:
afterEach(() => { queryClient.clear() });
setting cacheTime to 0 for your test, e.g. with: queryClient.setDefaultOptions({ queries: { cacheTime: 0 } })
using jest.useFakeTimers()
You could try defining a function like:
export function flushPromises() {
return new Promise((resolve) => setImmediate(resolve));
}
Then on your test before the expect:
await flushPromises();
More info here

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())
})
})

How to mock vue composable functions with jest

I'm using vue2 with composition Api, vuex and apollo client to request a graphql API and I have problems when mocking composable functions with jest
// store-service.ts
export function apolloQueryService(): {
// do some graphql stuff
return { result, loading, error };
}
// store-module.ts
import { apolloQueryService } from 'store-service'
export StoreModule {
state: ()=> ({
result: {}
}),
actions: {
fetchData({commit}) {
const { result, loading, error } = apolloQueryService()
commit('setState', result);
}
},
mutations: {
setState(state, result): {
state.result = result
}
}
}
The Test:
// store-module.spec.ts
import { StoreModule } from store-module.ts
const store = StoreModule
describe('store-module.ts', () => {
beforeEach(() => {
jest.mock('store-service', () => ({
apolloQueryService: jest.fn().mockReturnValue({
result: { value: 'foo' }, loading: false, error: {}
})
}))
})
test('action', async ()=> {
const commit = jest.fn();
await store.actions.fetchData({ commit });
expect(commit).toHaveBeenCalledWith('setData', { value: 'foo' });
})
}
The test fails, because the commit gets called with ('setData', { value: undefined }) which is the result from the original apolloQueryService. My Mock doesn't seem to work. Am I doing something wrong? Appreciate any help, thanks!
Try this :
// store-module.spec.ts
import { StoreModule } from store-module.ts
// first mock the module. use the absolute path to store-service.ts from the project root
jest.mock('store-service');
// then you import the mocked module.
import { apolloQueryService } from 'store-service';
// finally, you add the mock return values for the mock module
apolloQueryService.mockReturnValue({
result: { value: 'foo' }, loading: false, error: {}
});
/* if the import order above creates a problem for you,
you can extract the first step (jest.mock) to an external setup file.
You should do this if you are supposed to mock it in all tests anyway.
https://jestjs.io/docs/configuration#setupfiles-array */
const store = StoreModule
describe('store-module.ts', () => {
test('action', async ()=> {
const commit = jest.fn();
await store.actions.fetchData({ commit });
expect(commit).toHaveBeenCalledWith('setData', { value: 'foo' });
})
}

Mock Native Module Jest

In my React-Native application i wanna write some unit tests for my Native Libraries.
dataStorage.js
import RNDataStorage, {ACCESSIBLE} from "react-native-data-storage";
const dataStorage = {
setData: function (key, value) {
return RNDataStorage.set(key, value, {accessible: ACCESSIBLE.ALWAYS_THIS_DEVICE_ONLY})
.then(res => {
console.log(res);
return true;
})
},
}
export default dataStorage;
dataStorage.test.js
import dataStorage from '../../src/services/dataStorage'
jest.mock('react-native-data-storage', () => {
return {
RNDataStorage: {
set: jest.fn(),
}
};
});
it('Should return Access & RefreshToken', function () {
dataStorage.setData('John', 'Test');
});
When i run this setup i receive the error: TypeError: Cannot read property 'set' of undefined.
What is the correct way to mocks some modules? Thanks for any help
The module you are mocking is an ES6 module with a default export and a named export.
Mocking it like this should get your test running:
jest.mock('react-native-data-storage', () => {
return {
__esModule: true,
default: {
set: jest.fn(() => Promise.resolve('the response'))
},
ACCESSIBLE: {
ALWAYS_THIS_DEVICE_ONLY: true
}
};
});
Answer based on this post