Scott Shipp Scott Shipp - 29 days ago 5
TypeScript Question

Using Jasmine with Ionic is there a way to mock/stub a static namespace function call?

I'm new to this space so bear with me. I am working in an Ionic 2 project so it is using Angular 2, Typescript, and Jasmine for unit testing. I'm trying to write a unit test right now for a weird case. I have a third-party library that I import in a component with an import at the top like

import * as thirdparty from "thirdparty-library"
and later my component makes a call like
thirdparty.setup(someStuff, someMoreStuff, anotherFunc)
.

Really what I want to do is have a mock
thirdparty
with its own fake
anotherFunc
that I pass from the unit test. So is there a way to pass something in the constructor and have it override this
thirdparty
namespace? Thank you in advance

Answer

Functions being first class citizens, can be assigned new values. So if you want, you can always just do something like

let ogFunct;

beforeEach(() => {
  ogFunt = thirdparty.setup;
  thirdparty.setup = (arg1, arg2, arg3) => {
    console.log(`arg1 - arg2 - arg2`)
  }
});

afterEach(() => {
  thirdparty.setup = ogFunct;
});

Sometimes library type definitions will make the function read-only. In which case, you can't assign anything. Maybe in this case the better option would be to just abstract the third-party calls into a service. And just mock the service. You might even consider doing this anyway. Personally I think it is better design then using the third-party directly in the component.