Skip to content

Instantly share code, notes, and snippets.

@CHBaker
Created December 12, 2019 19:23
Show Gist options
  • Save CHBaker/dcaa78c490b530443fd6223e83b6605a to your computer and use it in GitHub Desktop.
Save CHBaker/dcaa78c490b530443fd6223e83b6605a to your computer and use it in GitHub Desktop.
dummy/fake/mock/stub
import { Component } from '@angular/core';
import { MyService } from './my-service.service';
export interface Item {
price: number;
name: string;
quantitiy: number;
}
export interface Groceries {
groceries: Item[];
totalItems: number;
totalPrice: number;
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
cart: Groceries;
verified: boolean;
deliveryDate: Date;
constructor(private myService: MyService) {}
/*
* Ex: Dummy
* fetchDiscounts is not needed to test this function, but it's dependency
* as a parameter make it necessary to supply the value
*/
updateGroceries(groceries: Item[], fetchDiscounts: (g: Groceries) => {}) {
this.cart.totalItems = groceries.length;
this.cart.totalPrice = groceries.reduce((acc: number, item: Item) => acc + item.price, 0);
fetchDiscounts(this.cart);
}
/*
* EX: Stub
* myService.getDeliveryDate is an external source
* independent of our function. The API could return any date
* based on it's own criteria. For testing, we can Stub getDeliveryDate
* and make it return a hard value of date
*/
getDeliveryDate(cart: Groceries) {
if (this.verified && cart.totalItems > 0) {
this.deliveryDate = this.myService.getDeliveryDate(cart)
}
}
/*
* EX: Fake
* myService.placeOrder is an external source
* independent of our function. The API does not return anything.
* For testing, we can Fake the method, since we don't need a value
* from it.
*/
/*
* EX: Mock
* similar to a stub, but interactive. Meaning we don't expect a value
* to be returned, but it should no the order of function calls. We can
* test if placeOrder is called using a mock.
*/
placeOrder() {
if (this.verified && this.deliveryDate) {
this.myService.placeOrder(this.cart, this.deliveryDate)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment