Posted onEdited onInjest Symbols count in article: 455Reading time ≈2 mins.
Jest useFakeTimer
Jest’s useFakeTimers function is used to mock timers in JavaScript. This is particularly useful when you have code that uses setTimeout, setInterval, or Date objects, and you want to control the passage of time in your tests.
Basic Usage
To use Jest’s useFakeTimers function, you need to call it before the code you want to test. You can then advance the timers using the advanceTimersByTime function.
Jest.runAllTimers() will run all pending timers. This is useful when you have multiple timers that need to be run in sequence. (Note, it will not work for nested timers)
There are also scenarios where you might have a recursive timer – that is a timer that sets a new timer in its own callback.
Jest.runOnlyPendingTimers() will only run the timers that are currently pending. This is useful when you want to run the timers that are currently in the queue, but not the ones that are scheduled to run in the future.
If you use jest.runAllTimers here, it will run all the timers and end up with an infinite loop.
待测试代码:
1 2 3 4 5 6 7 8 9 10 11 12 13
firstRound = false; secondRound = false;
infiniteTimerGame() { setTimeout(() => { this.firstRound = true; // Schedule the next game in 10 seconds setTimeout(() => { this.secondRound = true; this.infiniteTimerGame(); }, 10000); }, 1000); }
测试代码:
1 2 3 4 5 6 7 8 9 10 11
it('test infiniteTimerGame', () => { jest.useFakeTimers(); component.infiniteTimerGame(); // This will only run the timers that are currently pending(the outer timer) jest.runOnlyPendingTimers(); expect(component.firstRound).toBe(true);
// or jest.runOnlyPendingTimers(); This will run the newly created timer jest.advanceTimersByTime(10000); expect(component.secondRound).toBe(true); });
Selective faking
Sometimes your code may require to avoid overwriting the original implementation of one or another API. If that is the case, you can use doNotFake option. For example, here is how you could provide a custom mock function for performance.mark() in jsdom environment:
After you have finished testing, you should restore the original timers using jest.useRealTimers(), This can be done by invoking jest.useRealTimers() in the afterEach hook.
Posted onEdited onInjavascript Symbols count in article: 824Reading time ≈3 mins.
Creational Design Patterns
Factory Method
Define an interface for creating an object, but let subclasses decide which class to instantiate. Lets a class defer instantiation to subclasses.
Abstract Factory
Provides an interface for creating families of related or dependent objects without specifying their concrete class.
Builder
Separate the construction of a complex object from its representing so that the same construction process can create different representations.
Prototype
Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
Singleton
Ensure a class only has one instance and provide a global point of access to it. implementation
Application scenarios:
Logging: Singleton can be used to create a single log object that writes to a log file. This object can be used across the application without creating additional instances.
Database Connections: Singleton can be used to create a single database connection that is shared across the application. This can help to prevent an over-allocation of resources.
Configuration Settings: If your application has a set of configuration settings that need to be accessed in multiple places, a Singleton can be used to store these settings in one location.
Caching: Singleton can be used to create a cache that is accessible throughout the application. This can be useful for storing data that is expensive or time-consuming to fetch.
Shared Resource Access: If your application needs to control access to a shared resource, such as a printer or a file, you can use a Singleton to ensure that only one object is able to access the resource at a time.
Structural Design Patterns
Adapter
Convert the interface of a class into another interface clients expect. Lets classes work together that couldn’t otherwise because of incompatible interfaces. implementation
Bridge
Decouple an abstraction from its implementation so that the two can vary independently.
Composite
Compose objects into tree structures to represent part-whole hierarchies. Lets clients treat individual objects and compositions of objects uniformly.
Decorator
Attach additional responsibilities to an object dynamically. Provide a flexible alternative to extending functionality.
Facade
Provide unified interface to a set of interfaces in a subsystem. Defines a high-level interface that makes the subsystem easier to use.
Flyweight
Using sharing to support large numbers of fine grained objects efficiently.
Proxy
Provide a surrogate or placeholder for another object to control access to it.
Behavioral Design Patterns
Chain of Responsibility
Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chian the receiving objects and pass the request along the chain until an object handles it.
Command
Encapsulate a request as an object, thereby letting you parameterize clients with queues, queue or log requests, ans support undoable operations.
Interpreter
Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
Iterator
Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
Mediator
Define an object that encapsulates how a set of objects interact. Promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
Memento
Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later.
Observer
Define a one-to-many dependency between objects so that when on object changes state, all its dependents are notified and updated automatically.(Also known as Publish/Subscribe or Event-Subscriber pattern) implementation
Application scenarios
Event Handling: This is the most common use case in JavaScript. DOM events like clicks, key presses, form submissions etc., are handled using the Observer pattern.
Model-View-Controller (MVC) Architecture: In MVC architecture, the model notifies the view and the controller about changes in the data. This is done using the Observer pattern.
Web Sockets: Web sockets use the Observer pattern to listen for new messages from the server and update the UI accordingly.
React/Redux: In Redux, the store is the subject and the React components are the observers. When the state in the store changes, the components are notified to re-render.
Angular: Angular uses the Observer pattern in its event system and its HTTP module.
State
Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
Strategy
Define a family of algorithms, encapsulate each one, and make them interchangeable. Lets the algorithm vary independently from clients that use it. implementation
Template Method
Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.
Visitor
Represent an operation to be performed on the elements of an object structure. Lets ou define a new operation without changing the classes of the elements on which it operates.
Arrow functions create a closure over the this value of its surrounding scope, which means arrow functions behave if they are “auto-bound” — no matter how it’s invoked, this is bound to what it was when the function was created (the example above, the global object). The same applies to arrow functions created inside other functions: their thremains that of the enclosing lexical context.
In Node.js, the this keyword inside a module (a file) refers to the current module's exports, not the global object. This is because each file in Node.js is treated as a separate module and has its own scope. On the other hand, globalThis is a standard built-in object in JavaScript that always refers to the global object, regardless of where it is called. In the case of Node.js, globalThis refers to the global object which is global 看以下代码
1
console.log(this === globalThis); // true in browser, false in Node.js
1 2
console.log(this); // window in browser, {}(empty object) in Node.js, undefined in ES module console.log(globalThis); // window in browser, global object in Node.js
global context - Outside of any functions or classes(may be defined as an block or arrow functions in global scope)
global scope - In a programming environment, the global scope is the scope that contains, and is visible in, all other scopes. In client-side JavaScript, the global scope is generally the web page inside which all the code is being executed.
global object - A global object is an object that exists in global scope.
Browser - window
Node.js - global
Worker - self
globalThis - The global property allow one to access the global object regardless of the current environment.
Posted onEdited onInnest Symbols count in article: 356Reading time ≈1 mins.
nest.js - geting start
Installation
1
npm i -g @nestjs/cli
Create a new project
1
nest new project-name
Create a new module
1
nest g module module-name
Create a new controller
1
nest g controller controller-name
Create a new service
1
nest g service service-name
Create a new pipe
1
nest g pipe pipe-name
Create a new resource
1
nest g resource resource-name
Database
Nest.js is database agnostic, you can use any database you want. For example, you can use TypeORM, Sequelize, Mongoose, etc.
Install TypeORM with mysql driver
1
npm install --save @nestjs/typeorm typeorm mysql2
Troubleshooting
Error: Nest can’t resolve dependencies of the SearchHistoryService (?). Please make sure that the argument “SearchHistoryRepository” at index [0] is available in the SearchHistoryModule context.