间谍 return 值在使用茉莉花的服务测试中无法正常工作
Spy return value is not work correctly in Service test using jasmine
我无法在我的 Angular 测试中正确模拟我的注入服务中函数的 return 值。
我正在使用:
茉莉花 v2.8.0 和
茉莉花核心 v2.8.0
我简化了代码以使其更易于理解。这是...
这是我要测试的服务:
export class NetworkService {
testNumber = 0;
constructor(private networkReducerService: NetworkReducerService) {
this.testNumber = networkReducerService.getNumber();
}
}
这是我的spec.ts
describe('NetworkService', () => {
let service: NetworkService;
let networkReducerServiceSpy: jasmine.SpyObj<NetworkReducerService>;
beforeEach(() => {
const nRServiceSpy = jasmine.createSpyObj('NetworkReducerService', ['getNumber']);
TestBed.configureTestingModule({
providers: [NetworkService,
{provide: NetworkReducerService, useValue: nRServiceSpy}
]
});
service = TestBed.get(NetworkService);
networkReducerServiceSpy = TestBed.get(NetworkReducerService);
});
it('should have the following fields', () => {
networkReducerServiceSpy.getNumber.and.returnValue(1);
expect(networkReducerServiceSpy.getNumber).toHaveBeenCalled();
expect(service.testNumber).toBe(1);
});
});
我想在 NetworkReducerService
中模拟这个 getNumber 方法
@Injectable({
providedIn: 'root'
})
export class NetworkReducerService {
getNumber() {
return 1;
}
}
我收到以下错误:
错误:预期未定义为 1。
您 运行 遇到了 "a before b" 问题。您在 NetworkService
class 的构造函数中调用设置 testNumber
。因此,当您第一次创建 class 时会调用它 - 远在您更改间谍的值之前。要么在实例化服务之前设置值,要么重构 NetworkService
以在创建后可以通过调用而不是构造函数进行测试的方法中设置值。
我无法在我的 Angular 测试中正确模拟我的注入服务中函数的 return 值。
我正在使用:
茉莉花 v2.8.0 和 茉莉花核心 v2.8.0
我简化了代码以使其更易于理解。这是...
这是我要测试的服务:
export class NetworkService {
testNumber = 0;
constructor(private networkReducerService: NetworkReducerService) {
this.testNumber = networkReducerService.getNumber();
}
}
这是我的spec.ts
describe('NetworkService', () => {
let service: NetworkService;
let networkReducerServiceSpy: jasmine.SpyObj<NetworkReducerService>;
beforeEach(() => {
const nRServiceSpy = jasmine.createSpyObj('NetworkReducerService', ['getNumber']);
TestBed.configureTestingModule({
providers: [NetworkService,
{provide: NetworkReducerService, useValue: nRServiceSpy}
]
});
service = TestBed.get(NetworkService);
networkReducerServiceSpy = TestBed.get(NetworkReducerService);
});
it('should have the following fields', () => {
networkReducerServiceSpy.getNumber.and.returnValue(1);
expect(networkReducerServiceSpy.getNumber).toHaveBeenCalled();
expect(service.testNumber).toBe(1);
});
});
我想在 NetworkReducerService
@Injectable({
providedIn: 'root'
})
export class NetworkReducerService {
getNumber() {
return 1;
}
}
我收到以下错误:
错误:预期未定义为 1。
您 运行 遇到了 "a before b" 问题。您在 NetworkService
class 的构造函数中调用设置 testNumber
。因此,当您第一次创建 class 时会调用它 - 远在您更改间谍的值之前。要么在实例化服务之前设置值,要么重构 NetworkService
以在创建后可以通过调用而不是构造函数进行测试的方法中设置值。