7

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.

3
  • I think you are doing wrong way. you need to get data by using mock service Commented Feb 8, 2019 at 9:39
  • I could hardcode the data in the service but I want to stay DRY Commented Feb 8, 2019 at 9:52
  • I edited the question, require works in .spec.ts but not in the stub Commented Feb 8, 2019 at 10:02

1 Answer 1

6

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);
  }
};
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, that solves my problem so I accept the answer. I was just hoping I could just use json files... Thanks (I'll have to exclude these from the build though)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.