茉莉花间谍对象模拟方法返回不被覆盖

时间:2020-05-19 19:54:04

标签: angular testing mocking jasmine karma-runner

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

谢谢

1 个答案:

答案 0 :(得分:0)

尝试像之前一样添加以下行 productServiceMock = jasmine.createSpyObj(“ ProductService”,[“ getProduct”]); 在这个之上 productServiceMock.getProduct.and.returnValue(of(prod2));。

据我估计,您需要再次进行监视,然后才需要新的返回值。