Write test for nanostores
Mohammad Jawad barati
Software Engineer | Fullstack Engineer | Microservices | TS/JS | Python | IaC | AWS | TDD | BDD | Automation | CI/CD
why I wrote this post in the first place?
Lack of tut and doc around this awesome library that makes our lives easier.
Why and How we should do?
Why:
Because then we can separate logic and view from each other in a react application. Sounds cool, right. Just think about it, your HTML code is not full of logic & also your logic is not all over the place.
How:
Just create a file besides your normal tsx file and name whatever you like. I usually name it after my states.
领英推荐
Inside it you need to create your atom (or we can look at it the same way we were looking at the useState states)
import { atom, action } from 'nanostores
type User = { name: string }
const users = atom<User[]>([])
const addUser = action(users, "addUser", (users, user: User) => {
? users.set([...users.get(), user]);
})
export const UserStore = {
states: { users },
actions: { addUser }
}
And now the test cases in Jest
import {
allTasks,
cleanStores,
keepMount,
} from 'nanostores';
describe("UserStore", () => {
afterEach(() => {
// cleanStores means clean stores from listeners not reset the stores to their initial value
cleanStores(UserStore.states.users)
// To have a empty array inside the users state after each test
UserStore.states.users.set([])
})
describe("addUser", () => {
it("should add user", async () => {
const user = {name: "Kasir"};
keepMount(UserStore.states.users);
UserStore.actions.addUser(user);
// Just if the action is async - I mean the callback we passed to the action - which in our case is not. But I wrote it JFYI
await allTasks();
expect(UserStore.states.users.get()).toEqual(user)
})
})
})
I hope this will help you to write a good app in React. :heart:
reference: https://github.com/nanostores/nanostores/issues/167
?????Trusted IT Solutions Consultant | Technology | Science | Life | Author, Tech Topics | Goal: Give, Teach & Share | Featured Analyst on InformationWorth | TechBullion | CIO Grid | Small Biz Digest | GoDaddy
1 年Mohammad, thanks for sharing!