I have an angular project in which I use jest as test runner.
I use the pipe 'translate' for internationalisation, but in consequence in most of my test spec I have to add:
@Pipe({
name: 'translate'
})
export class TranslateMockPipe implements PipeTransform {
public name: string = 'translate';
public transform(query: string, ...args: any[]): any {
return query;
}
}
declarations: [..., TranslateMockPipe],
My issue is, I have to add this code in all my spec file.
Any idea how I can do it automatically in all my spec? ( maybe by putting it in the setup-jest.ts ? )
CodePudding user response:
I'm also using jest in my project. I am although not creating mocks for the pipes. As I do actually want to test the pipes and not mock them. Could you provide an example on how you use the pipe in your tests?
Below is an example of how I test a pipe that transforms bytes into presentable strings, if that helps.
import { FormatBytesPipe } from '@jfs/shared/pipes/format-bytes.pipe';
describe('Pipe: Format Bytes', () => {
let pipe: FormatBytesPipe;
beforeEach(() => {
pipe = new FormatBytesPipe();
});
it('should transform 0 to "0 Bytes"', () => {
expect(pipe.transform(0)).toEqual('0 Bytes');
});
it('should transform 1024 to "1 KB"', () => {
expect(pipe.transform(Math.pow(1024, 1))).toEqual('1 KB');
});
it('should transform 1024^2 to "1 MB"', () => {
expect(pipe.transform(Math.pow(1024, 2))).toEqual('1 MB');
});
it('should transform 1024^3 to "1 GB"', () => {
expect(pipe.transform(Math.pow(1024, 3))).toEqual('1 GB');
});
it('should transform 1024^4 to "1 TB"', () => {
expect(pipe.transform(Math.pow(1024, 4))).toEqual('1 TB');
});
it('should transform 1024^5 to "1 PB"', () => {
expect(pipe.transform(Math.pow(1024, 5))).toEqual('1 PB');
});
it('should transform 1024^6 to "1 EB"', () => {
expect(pipe.transform(Math.pow(1024, 6))).toEqual('1 EB');
});
it('should transform 1024^7 to "1 ZB"', () => {
expect(pipe.transform(Math.pow(1024, 7))).toEqual('1 ZB');
});
it('should transform 1024^8 to "1 YB"', () => {
expect(pipe.transform(Math.pow(1024, 8))).toEqual('1 YB');
});
});
CodePudding user response:
You might consider using a third-party testing library like ng-mocks
, which allows you to mock easily services, components, pipes and many other things.
Have a look at official documentation on how to mock pipes.