index.ts
:
export const toggleClass = (elementDOM, className) => {
if (elementDOM.classList.contains(className)) {
elementDOM.classList.remove(className);
} else {
elementDOM.classList.add(className);
}
};
index.spec.ts
:
import { toggleClass } from '.';
describe('toggleClass', () => {
const mockedElementDOM = { classList: { contains: jest.fn(), remove: jest.fn(), add: jest.fn() } };
it('should remove the class', () => {
const className = 'a';
mockedElementDOM.classList.contains.mockReturnValueOnce(true);
toggleClass(mockedElementDOM, className);
expect(mockedElementDOM.classList.remove).toBeCalledWith('a');
});
it('should add the class', () => {
const className = 'a';
mockedElementDOM.classList.contains.mockReturnValueOnce(false);
toggleClass(mockedElementDOM, className);
expect(mockedElementDOM.classList.add).toBeCalledWith('a');
});
});
PASS src/stackoverflow/45918386/index.spec.ts
toggleClass
â should remove the class (4ms)
â should add the class (1ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 3.575s, estimated 9s
源代码:
https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/45918386