I'm not able to mock chained function of sequelize.
In following example I can mock Query 1, but not Query 2
something.service.ts
// Query 1
await this.table2.findAll<table2>({
attributes: [
'field1'
],
where: {
id: someId
},
});
// Query 2
// returns []
let bill1: any = await this.table2.sequelize.query(`
SELECT
aa.field1,
bg.field2
FROM
table1 aa,
table2 bg
WHERE
bg.id = '${billId}'
AND
aa.id = bg.aggr_id;
`);
something.service.spec.ts
beforeEach(async () => {
const module = await Test.createTestingModule({
providers: [
{
provide: getModelToken(table2),
useValue: {
// mock successful for query 1
findAll: jest.fn(() => [{}]),
// mock fails for query 2
sequelize: jest.fn().mockReturnValue([]),
query: jest.fn().mockReturnValue([]),
'sequelize.query': jest.fn().mockReturnValue([]),
},
}
],
}).compile();
With this code I'm receiving (for Query 2)
TypeError: this.table2.sequelize.query is not a function
I tried with following code, no luck
sequelize: jest.fn().mockReturnValue([]),
query: jest.fn().mockReturnValue([]),
'sequelize.query': jest.fn().mockReturnValue([]),
sequelize: jest.fn().mockReturnValue({
query: jest.fn(() => [])
})
You can utilize jest.fn().mockReturnThis() to mock the chained function in jest. I have tested this on mocking the TypeORM repository, something like this:
repository.mock.ts
export const mockedRepository = {
find: jest.fn(),
createQueryBuilder: jest.fn(() => ({ // createQueryBuilder contains several chaining methods
innerJoinAndSelect: jest.fn().mockReturnThis(),
getMany: jest.fn(),
})),
};
Somewhere in your service for example:
test.service.ts
//
async findAll(){
return await this.repository
.createQueryBuilder('tableName')
.innerJoinAndSelect('tableName.relation','relation' )
.getMany();
}
//
And finally the unit test spec:
test.service.spec.ts
const module = await Test.createTestingModule({
providers: [
TestService,
{
provide: getRepositoryToken(Test),
useValue: mockedRepository,
}
],
}).compile();
testService =
module.get<TestService>(TestService);
testRepository = module.get<Repository<Test>>(
getRepositoryToken(Test),
);
});
describe('when findAll is called', () => {
beforeEach(() => {
mockedRepository.createQueryBuilder.getMany.mockResolvedValue([]);
});
it('should call innerJoinAndSelect method once', async () => {
await testService.findAll();
expect(mockedRepository.createQueryBuilder.innerJoinAndSelect).toHaveBeenCalledTimes(1);
});
it('should return an empty array', async () => {
expect(await testService.findAll()).toBe([]);
});
});
This is not a real working example but I hope you get the idea.
Issue was with the problem statement itself, this.table.sequelize is an object NOT a function to be chained, following solution worked to mock it.
sequelize: { query: jest.fn(() => []) }
To mock chained functions Farista's solution works.
Related
I’m having a hard time to mock/test this useLazyQuery case; the hook in the screen:
const [
getSpecificReport,
{ loading: contentLoading, error: contentError, data: content },
] = useLazyQuery<SpecificReportResponse>(
SPECIFIC_REPORT(testResultsData?.getTestResults.testType),
{
client: cmsClient, // <- this is a specific ApolloClient
fetchPolicy: "network-only",
onCompleted: () => {
setScreenData();
},
onError: (err) => {
// (...) omitted for simplification
},
}
);
The mock:
const mocks = [{
request: {
query: SPECIFIC_REPORT('Report Title'),
fetchPolicy: 'network-only',
},
result: {
data: {
allReports: [getReportTestData()],
} as SpecificReportResponse,
},
}]
The test:
...
const { getByText, getAllByText } = render(
<MockedProvider
mocks={mocks}
addTypename={false}
>
<ResultsScreen {...mockProps} />
</MockedProvider>
);
await waitFor(() => {
new Promise((resolve) => setTimeout(resolve, 3000));
expect(getByText(/Something/)).toBeTruthy();
(...)
}
...
What happens is that the screen (ResultsScreen) just acts as if not received the data, i.e. the first expectation fails.
I noticed that if I take off the specific client from the hook, the test works fine - but not the screen, which depends on that.
I wonder if I should pass a “mocked client” to the mocks[0].request or something - I already tried to do it, but no success so far.
Does anyone have any ideas?
Thanks in advance!
I solved it by mocking the client like this (didn't change anything else):
...
const mockCmsClient = new ApolloClient({
link: ApolloLink.from([ApolloLink.empty(), ApolloLink.empty(), ApolloLink.empty()]),
cache: new InMemoryCache(),
});
jest.mock('../../my-module-with-exported-client', () => ({
...jest.requireActual('../../my-module-with-exported-client'),
cmsClient: mockCmsClient,
}));
...
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())
})
})
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' });
})
}
I have a validation pipe to check input that works when I manually create a product(using postman), but it doesn't check when I run tests. any explanations?
my validator:
#Injectable()
export class JoiValidationPipe implements PipeTransform {
constructor(private schema: ObjectSchema) {}
transform(value: any, metadata: ArgumentMetadata) {
const { error } = this.schema.validate(value);
if (error) {
throw new HttpException('Validation failed', HttpStatus.BAD_REQUEST);
}
return value;
}
}
my controller:
#UsePipes(new JoiValidationPipe(productSchema))
#Post()
async create(#Body() createProductDto: CreateProductDto): Promise<Product> {
return (await this.productsService.create(createProductDto)).product;
}
my test:
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [ProductsController],
providers: [ProductsService],
}).compile();
controller = module.get<ProductsController>(ProductsController);
service = module.get<ProductsService>(ProductsService);
});
describe('create()', () => {
it('should fail to add a new product', async () => {
const result: Product = {
name: 'p',
price: -100,
category: 'junk',
};
expect(await controller.create(result)).toBe(result);
});
});
my schema:
export const productSchema: ObjectSchema = object({
createProductDto: object().keys({
name: string().min(5).required(),
price: number().integer().min(0).default(0),
category: string().min(5).required(),
}),
});
Pipes don't run unless you're going through the HTTP request. Same for other enhancers like guards and interceptors. If you want to test the pipe you can do that with supertest and e2e tests, or you can test the schema directly with joi in a different test suite
I am trying to mock and spy on the redis set method in my nestjs setup, but I don't think that it is working as it should.
const mockRedis = {
set: jest.fn().mockResolvedValue(undefined),
};
const mockRedisService = {
getClient: jest.fn(() => mockRedis),
};
beforeEach(async () => {
const moduleRef = await Test.createTestingModule({
providers: [
{ provide: RedisService, useValue: mockRedisService },
],
}).compile();
});
it('...',() => {
const redisSetSpy = jest.spyOn(mockRedis, 'set');
myTestedMethod();
expect(redisSetSpy).toBeCalledWith(/* args here */);
})
I suspect that it is not possible to use spyOn with a nested method as set in this context? How should I mock redis to be able to use spyOn on set? The library used for redis in this case is nestjs-redis.
You don't have to use spyOn to check the arguements that have been passed to the function. You can simply create a jest.fn():
let mockRedisSet;
// Function that creates the testing app.
const createApp = () => {
const mockRedis = {
set: mockRedisSet,
};
const mockRedisService = {
getClient: jest.fn(() => mockRedis),
};
const moduleRef = await Test.createTestingModule({
providers: [{ provide: RedisService, useValue: mockRedisService }],
}).compile();
};
// For each test, set default mock and create testing app.
beforeEach(async () => {
mockRedisSet = jest.fn().mockResolvedValue(undefined);
createApp();
});
describe("...", () => {
// For each sub tests, set default mock and create testing app.
beforeEach(async () => {
mockRedisSet = jest.fn().mockResolvedValue(/* Specific value for sub tests */);
createApp();
});
it("...", () => {
myTestedMethod();
// Check which arguments was passed to the mock function.
expect(mockRedisSet).toHaveBeenCalledWith(/* args here */);
});
});
Creating a mock is much simpler this way as you only have to create the mocked objects and test the functions the use.
Here your spy is mockRedisSet and I reorganized your testing file so the spy function has a default value that can be overridden for specific tests. You have more control on the testing value and a default value reset for each tests so that tests don't interfer with each other.