茉莉花监视对象模拟方法返回未被覆盖



我有这个全局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 上设置的值,而不是被特定测试中的语句覆盖?

谢谢

尝试添加以下行,就像您在每个行之前所做的那样 productServiceMock = jasmine.createSpyObj("ProductService", ["getProduct"](; 在这个之上 productServiceMock.getProduct.and.returnValue(of(prod2((;.

正如我猜的那样,在需要新的返回值之前,您需要再次监视。

最新更新