I try to mock data in my jasmine tests.
In a component spec I use:
describe('MyComponent', () => {
const user: User = require('../../mocks/user.json');
I a service stub that I put inside /src/mocks/services/service.stub.ts
import { Observable, of } from 'rxjs';
export const MyServiceStub = {
users: require('../../mocks/users.json'),
getUsers(): Observable<any> {
return of(this.users);
}
};
With this npm run test works but the app doesn't compile because of
ERROR in src/app/mocks/services/UserServiceStub.ts(4,15): error TS2304: Cannot find name 'require'.
I've tried modifying tsconfig.json with
"compilerOptions": {
"resolveJsonModule": true,
"esModuleInterop": true
}
And import mocks json with:
import * as users from '../../mocks/users.json';
This destroyed all my imports like momentJS (import * as moment from 'moment')
I read I could just add
"allowSyntheticDefaultImports": true
But this didn't help...
What's the right way to import a json file in my tests?
EDIT: I forgot to say that require works in my spec files, it just fails when I use it in /src/mocks/services/MyService.stub.ts
I modified the stubbed service to be a class and changed the provider to use useClass instead of useValue but this didn't help.
You can have something like:
export const USER_OBJECTS: User[] = [
{
'firstName': 'Ana',
'lastName': '..',
'fullName': '..',
'userName': '..',
'email': '...'
} as User,
{
'firstName': 'Lisa',
'lastName': '..',
'fullName': '..',
'userName': '...',
'email': '...'
} as User
];
In your mocks/users.json.ts
and import it into your stubs file like:
import {USERS_OBJECTS} from '../mocks/users.json.ts';
Then your stub service would look like:
export const MyServiceStub = {
users: require('../../mocks/users.json'),
getUsers(): Observable<User[]> {
return of(USER_OBJECTS);
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With