【发布时间】:2020-05-19 19:54:04
【问题描述】:
我有这个全局的 beforeEach,我在其中定义了一些 serviceMocks 及其返回值。在这种情况下,通常我想退回名称为“Prod1”的产品。
beforeEach(async(() => {
//MOCKS
let plansPrices:{[name:string]:number} = {["M"]:2, ["D"]:0.5};
let prod:Product = {name: "Prod1", licenses:[], typeSubs:["M","D"],photoAvailable:false,description: "The description",webLink:"www.c.com",photoSrc:"",plansPrices:plansPrices,sku:null, active:true, trialDays:9, mode:"Both"};
productServiceMock = jasmine.createSpyObj("ProductService", ["getProduct"]);
productServiceMock.getProduct.and.returnValue(of(prod));
TestBed.configureTestingModule({
declarations: [ CatalogProductComponent ,CardFormComponent ],
imports: [ ReactiveFormsModule,MatGridListModule,MatIconModule,MatCardModule, MatSelectModule,MatOptionModule,NgxPaginationModule, MatSnackBarModule,HttpClientModule, FormsModule ],
providers: [
{ provide: ProductService, useValue:productServiceMock },
...
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CatalogProductComponent);
component = fixture.componentInstance;
domHelper = new DOMHelper(fixture);
});
但在特定测试中,我想覆盖该返回值,返回一个名为“Prod2”的产品。这是测试:
it('should subscribe to free trial', () => {
let plansPrices:{[name:string]:number} = {["M"]:2, ["D"]:0.5};
let prod2:Product = {name: "Prod2", licenses:[], typeSubs:["M","D"],photoAvailable:false,description: "The description",webLink:"www.c.com",photoSrc:"",plansPrices:plansPrices,sku:null, active:true, trialDays:9, mode:"Both"};
productServiceMock.getProduct.and.returnValue(of(prod2)); //Seems that this isn't working
fixture.detectChanges(); //Calls the
let prodName = domHelper.getText("#productName");//Gets the text of an <a id="productName></a> setted on ngOnInit()
expect(prodName).toBe("Prod2"); //This is failing, prodName is "Prod1"
});
为什么它仍然返回在 beforeEach 上设置的值,而不是被特定测试上的语句覆盖?
谢谢
【问题讨论】:
-
请同时分享相关组件的代码。我假设您要模拟的
getProduct调用在实际模拟发生之前被调用。 -
@PhilippMeissner 你让我想到了这个问题,我遇到了问题:getProduct 是由构造函数而不是 ngOnInit 调用的。谢谢!
-
是的,这是人们经常遇到的问题。很高兴它有帮助。
标签: angular testing mocking jasmine karma-runner