模拟服务中的依赖项

时间:2019-12-03 11:30:43

标签: angular typescript jestjs

我正在尝试模拟服务中的依赖项。我不知道出了什么问题。.虽然它不是一个很好的类来测试,但它全都涉及代码覆盖率-这就是服务

@Injectable()
export class SessionService {
    constructor(private sessionStore: UserStore){}

    login(userData: User) {
        this.sessionStore.login(userData);
    }
    logout(){
        this.sessionStore.logout();
    }
}

依赖性UserStore看起来像这样:

export function createInitialState(): User {
    return {
        id: 0, password: "", role: undefined, username: "",
    }
}
@Injectable()
@StoreConfig({ name: 'session', resettable: true })
export class UserStore extends Store<User> {
    constructor() {
        super(createInitialState());
    }

    login(user: User){
        this.update(user);
    }

    logout(){
        this.reset();
        this.update(createInitialState());
    }

    getCurrentUser(){
        return this.getValue();
    }
}

单元测试:

describe('SessionService', () => {
   // @ts-ignore
   let sessionService: SessionService;
   let userStoreMock;
   beforeEach(() => {

       userStoreMock = {
           login: jest.fn(),
           logout: jest.fn()
       };

       TestBed.configureTestingModule({
           providers:[{ provide: UserStore, useValue: userStoreMock}]
       });

       sessionService = TestBed.get(SessionService);
   });

    it('should be defined', () => {
        expect(sessionService).toBeDefined();
    })
});

我得到的错误是:

TypeError: Cannot read property 'getComponentFromError' of null

2 个答案:

答案 0 :(得分:1)

为了模拟服务,您应该从要使用的方法中创建一个间谍对象(jasmine.createSpyObj),然后模拟这些方法的返回值。

例如:

let mockService;

mockService = jasmine.createSpyObj(['methodOne', 'methodTwo']);
mockService.methodOne.and.returnValue(of(MOCKED_DATA_1));
mockService.methodTwo.and.returnValue(of(MOCKED_DATA_2));

,然后在您的configureTestingModule的提供程序中设置该模拟服务:

TestBed.configureTestingModule({
   ...
   providers: [
       ...
       {
           provide: MyService, useValue: mockService
       }
   ]
})

答案 1 :(得分:1)

SessionService未添加到提供商列表。

配置应为

TestBed.configureTestingModule({
    providers:[
        SessionService,
        { provide: UserStore, useValue: userStoreMock}
    ]
});

此后,如果遇到相同的问题,请在beforeEach()内添加以下代码。

TestBed.resetTestEnvironment();
 TestBed.initTestEnvironment(BrowserDynamicTestingModule,
    platformBrowserDynamicTesting());

Test.ts

import 'core-js/es7/reflect';
import 'zone.js/dist/zone';
import 'zone.js/dist/zone-testing';
import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';

declare const require: any;

// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);